1
import { type Context, copyJson, type JsonRepresentation } from "@earendil-works/chord";2
import { ConversationBusy } from "../errors.ts";3
import type { SessionImpl } from "../session/session.ts";4
import type {5
CommitPublication,6
ConversationId,7
JsonObject,8
Storage,9
SubmissionId,10
SubmissionRecord,11
Tx,12
} from "../types.ts";13
import { startRun } from "./generation.ts";14
import {15
appendInput,16
applyBoundary,17
hasQueuedReset,18
InboxDoc,19
isDisplayOnly,20
isStale,21
pickInputEntry,22
prepareBoundary,23
type QueueModes,24
removeInboxItem,25
} from "./inbox.ts";26
import { LiveDoc } from "./live.ts";27
import type { InputEntry, SettledSubmissionRecord, Submission, SubmissionDraft, UserInput } from "./types.ts";28
import { closedError, Waiters } from "./util.ts";30
type AbortResult = "aborted" | "already_placed" | "settled";32
/** Admission, waits, and withdrawal of the durable submissions of one Harness. */33
export class Submissions {34
readonly #session: SessionImpl;35
readonly #storage: Storage;36
readonly #now: () => number;37
/** Read at each admission, on the Session line. */38
readonly #queueModes: () => QueueModes;39
/** Enable task scheduling; submitting or waiting asks for progress. */40
readonly #resume: () => void;41
readonly #waiters = new Waiters<SubmissionId, SettledSubmissionRecord>();42
#closed = false;44
constructor(45
session: SessionImpl,46
storage: Storage,47
now: () => number,48
queueModes: () => QueueModes,49
resume: () => void,50
) {51
this.#session = session;52
this.#storage = storage;53
this.#now = now;54
this.#queueModes = queueModes;55
this.#resume = resume;56
session.observeCommits((publication) => this.#observe(publication));57
session.subscribeClose(() => {58
this.#closed = true;59
this.#waiters.rejectAll(closedError(this.#session));60
});61
}63
/** Admit a submission in one commit; see `admitSubmission()`. */64
async submit(conversationId: ConversationId, draft: SubmissionDraft, context: Context): Promise<Submission> {65
this.#resume();66
const id = await this.#session.commitWith(67
(tx) => admitSubmission(tx, conversationId, draft, this.#now(), this.#queueModes()),68
context,69
);70
return new SubmissionHandle(id, this);71
}73
/** Handle for an existing submission, or `undefined`. */74
async get(id: SubmissionId, context: Context): Promise<Submission | undefined> {75
const record = await this.#session.readOnLine(() => this.#storage.submission(id, context));76
return record === undefined ? undefined : new SubmissionHandle(record.id, this);77
}79
async status(id: SubmissionId, context: Context): Promise<SubmissionRecord> {80
const record = await this.#session.readOnLine(() => this.#storage.submission(id, context));81
if (record === undefined) throw new Error(`Submission ${id} does not exist`);82
return record;83
}85
async wait(id: SubmissionId, context: Context): Promise<SettledSubmissionRecord> {86
this.#resume();87
// Check and register on the line so no settling publication falls between them.88
const found = await this.#session.readOnLine(async () => {89
const record = await this.#storage.submission(id, context);90
if (record === undefined) throw new Error(`Submission ${id} does not exist`);91
if (isSettled(record)) return { promise: Promise.resolve(record) };92
// Close rejects registered waiters synchronously and may begin during the read.93
if (this.#closed) throw closedError(this.#session);94
return { promise: this.#waiters.add(id, context) };95
});96
return found.promise;97
}99
/** Withdraw a queued submission and remove its inbox item; placed inputs and settled submissions are reported. */100
abort(id: SubmissionId, context: Context, conversationId?: ConversationId): Promise<AbortResult | "not_found"> {101
return this.#session.commitWith(async (tx) => {102
const record = await tx.submission(id);103
if (record === undefined || (conversationId !== undefined && record.conversationId !== conversationId)) {104
return "not_found";105
}106
if (record.status === "queued") {107
tx.settleSubmission(id, { status: "unanswered", reason: "aborted" });108
await removeInboxItem(tx, record.conversationId, id);109
return "aborted";110
}111
return record.status === "placed" ? "already_placed" : "settled";112
}, context);113
}115
#observe(publication: CommitPublication): void {116
for (const change of publication.changes) {117
if (change.type !== "submission" || !isSettled(change.value)) continue;118
this.#waiters.resolve(change.value.id, change.value);119
}120
}121
}123
class SubmissionHandle implements Submission {124
readonly id: SubmissionId;125
readonly #submissions: Submissions;127
constructor(id: SubmissionId, submissions: Submissions) {128
this.id = id;129
this.#submissions = submissions;130
}132
status(context: Context): Promise<SubmissionRecord> {133
return this.#submissions.status(this.id, context);134
}136
wait(context: Context): Promise<SettledSubmissionRecord> {137
return this.#submissions.wait(this.id, context);138
}140
async abort(context: Context): Promise<AbortResult> {141
const result = await this.#submissions.abort(this.id, context);142
if (result === "not_found") throw new Error(`Submission ${this.id} does not exist`);143
return result;144
}145
}147
function isSettled(record: SubmissionRecord): record is SettledSubmissionRecord {148
return record.status === "done" || record.status === "unanswered";149
}151
/** Reject an input entry an untyped caller got wrong: its kind must be a non-empty string outside the `pi.` prefix. */152
function checkInputEntry(entry: InputEntry): void {153
const { kind } = entry;154
if (typeof kind !== "string" || kind.length === 0 || kind.startsWith("pi.")) {155
throw new TypeError(156
`An input entry's kind must be a non-empty string not starting with "pi.", got ${String(kind)}`,157
);158
}159
}161
/**162
* Admit a submission inside a commit (spec §6); `Conversation.submit()` and conversation-owned compactions share it. A163
* known request ID returns its existing submission without writing. A display-only write (only `kind` and `data`) is164
* appended and settled `done` at once, busy or not, as it changes nothing the model sees; only behind a queued reset it165
* queues, so it lands after the reset instead of before it in the context the reset ends. A busy conversation queues anything else in166
* `pi.inbox`, or rejects `whenBusy: "reject"` input with `ConversationBusy`. An idle conversation with queued items167
* queues it behind them and runs a final boundary. Otherwise idle input places its entry (`pi.user`, or the input's168
* own) and starts a run, and an idle write appends its entry and settles `done`, or `stale` when its head reaches169
* before the active range.170
*/171
export async function admitSubmission(172
tx: Tx,173
conversationId: ConversationId,174
draft: SubmissionDraft,175
now: number,176
queueModes: QueueModes,177
): Promise<SubmissionId> {178
if (draft.type === "input" && draft.entry !== undefined) checkInputEntry(draft.entry);179
if (draft.requestId !== undefined) {180
const existing = await tx.submissionByRequest(conversationId, draft.requestId);181
if (existing !== undefined) {182
if (existing.type !== draft.type) {183
throw new Error(`Request ${draft.requestId} already identifies a submission of type ${existing.type}`);184
}185
return existing.id;186
}187
}188
const requestId = draft.requestId === undefined ? {} : { requestId: draft.requestId };189
if (190
draft.type === "write" &&191
isDisplayOnly(draft.entry) &&192
!hasQueuedReset((await tx.doc(InboxDoc, conversationId)).items)193
) {194
const entry = await tx.appendEntry(conversationId, draft.entry);195
const write = { conversationId, ...requestId, type: "write", status: "done", entry: entry.id } as const;196
return (await tx.createSubmission(write)).id;197
}198
const live = await tx.doc(LiveDoc, conversationId);199
const busy = live.run !== undefined;200
if (busy && draft.type === "input" && draft.whenBusy === "reject") throw new ConversationBusy(conversationId);201
// A boundary reads the table, so it is prepared before the first table write; a busy one needs none.202
const boundary = busy ? undefined : await prepareBoundary(tx, conversationId, queueModes);203
if (boundary === undefined || boundary.inbox.items.length > 0) {204
const { id } = await tx.createSubmission({205
conversationId,206
...requestId,207
type: draft.type,208
status: "queued",209
});210
// Hosts may leave optional fields `undefined`; drafts take strict JSON.211
const value = copyJson(draft.type === "write" ? draft.entry : draft.content, {212
omitUndefinedProperties: true,213
});214
const items = (boundary?.inbox ?? (await tx.doc(InboxDoc, conversationId))).items;215
if (draft.type === "write") items.push({ id, mode: "write", entry: value as JsonObject });216
else {217
const mode = draft.whenBusy === "steer" ? "steer" : "followUp";218
const content = value as JsonRepresentation<UserInput>;219
const entry = draft.entry === undefined ? {} : { entry: pickInputEntry(draft.entry) };220
items.push({ id, mode, content, ...entry });221
}222
if (boundary === undefined) return id;223
const { users } = await applyBoundary(tx, boundary, "final", now);224
if (users.length > 0) await startRun(tx, conversationId, live, users);225
return id;226
}227
if (draft.type === "write") {228
if (isStale(boundary, draft.entry)) {229
const stale = { status: "unanswered", reason: "stale" } as const;230
return (await tx.createSubmission({ conversationId, ...requestId, type: "write", ...stale })).id;231
}232
const entry = await tx.appendEntry(conversationId, draft.entry);233
const write = { conversationId, ...requestId, type: "write", status: "done", entry: entry.id } as const;234
return (await tx.createSubmission(write)).id;235
}236
const entry = await appendInput(tx, conversationId, draft.content, draft.entry, now);237
const input = { conversationId, ...requestId, type: "input", status: "placed", entry: entry.id } as const;238
const { id } = await tx.createSubmission(input);239
await startRun(tx, conversationId, live, [id]);240
return id;241
}