feat(ai-harness): Tau #1755
main fromrefs/pull/1755/headmerged by AlemTuzlak View on GitHub- packages/ai-harness/src/resume.ts lines 97 to 103OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +83,21 @@83+84+/**85+ * Hold the lease on run `runId` and renew it. Returns the function that stops86+ * the renewal. A host that stops lets the lease expire, so recovery can tell87+ * the run is dead.88+ */89+export async function holdRunLease(90+ runs: RunStore | undefined,91+ runId: string,92+ hostId: string,93+ lease?: LeaseOptions,94+): Promise<() => void> {95+ if (!runs) return () => {}96+ const ttlMs = lease?.ttlMs ?? LEASE.ttlMs97+ const renew = () =>98+ runs.update(runId, {99+ leaseOwner: hostId,100+ leaseExpiresAt: Date.now() + ttlMs,101+ })102+ await renew()103+ const timer = setInterval(() => void renew(), lease?.renewMs ?? LEASE.renewMs)@@ -0,0 +150,21 @@150+ const next: AnyTool = {151+ ...tool,152+ execute: (args: unknown, context?: ToolExecutionContext) => {153+ const id = context?.toolCallId154+ if (!context || id === undefined) return execute(args, context)155+ context.detach = (work) =>156+ new Promise((moved) => {157+ this.detachable.set(id, () => {158+ this.logJob(id, false)159+ moved(160+ `The job moved to the background. Its id is ${id}. You get a note when it ends.`,161+ )162+ // Like other background jobs: a note that wakes the session.163+ work164+ .then(165+ (result) =>166+ `Background job ${id} ended.\n${typeof result === 'string' ? result : JSON.stringify(result)}`,167+ (error: unknown) =>168+ `Background job ${id} failed: ${error instanceof Error ? error.message : String(error)}`,169+ )170+ .then((text) => this.pluginApi().note(text, { wake: true }))packages/ai-harness/src/session/turn.ts line 86OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +66,21 @@66+export abstract class SessionTurn<67+ THarness extends AnyHarness = AnyHarness,68+> extends SessionAgents<THarness> {69+ /**70+ * Run a plugin command. Its input is checked against the command's schema.71+ * `principal` is who runs it. Default: the principal that opened the72+ * session. The log keeps it, and the command gets that user's credentials.73+ */74+ command(75+ name: string,76+ input?: unknown,77+ options?: { principal?: Principal },78+ ): Operation<unknown> {79+ const operation = new OperationImpl<unknown>(80+ 'command',81+ this.feed,82+ (target) => this.cancel(target.id),83+ )84+ this.operations.set(operation.id, operation)85+ const principal = options?.principal ?? this.principal86+ void this.executeCommand(operation, name, input, principal)
github-actions[bot](GitHub profile, opens in a new tab) assignedtombeckenham
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
tombeckenham reviewed
@@ -0,0 +835,21 @@835+ const value = result !== undefined ? result : text836+ // The run record and the log keep how the agent ended, so recovery837+ // leaves it alone. After a log failure, another host owns the thread and838+ // decides how the run ended, so this host writes neither.839+ const end = async (840+ run: Pick<RunRecord, 'status'> &841+ Partial<Pick<RunRecord, 'error' | 'result'>>,842+ settlement: Pick<InputSettlement, 'outcome' | 'error'>,843+ ) => {844+ if (this.logFailure) return845+ await runs?.update(operation.id, { ...run, finishedAt: Date.now() })846+ // A refused append stops the session. The operation still ends. The847+ // steers that joined the run settle with it, in one append.848+ const joined = this.joinedInputs(operation.id, inputId)849+ await this.settle(850+ ...[inputId, ...joined].map((id) => ({851+ inputId: id,852+ operationId: operation.id,853+ ...settlement,854+ })),855+ ).catch(() => {})@@ -0,0 +117,21 @@117+ }118+ checked = result.data119+ }120+ operation.setStatus('running')121+ await this.applied(inputId, operation.id)122+ this.publishStarted(operation)123+ try {124+ const result: unknown = await entry.command.run(checked, {125+ signal: operation.abortController.signal,126+ // The command acts for its sender, also while another user's turn runs.127+ session: principal ? this.pluginApi(principal) : this.services.session,128+ ...(principal ? { principal } : {}),129+ credentials: this.credentialsOf(principal),130+ })131+ operation.publish(132+ customEvent('harness.command.result', {133+ name,134+ result: compactForModel(result),135+ }),136+ )137+ operation.finish('completed', result)@@ -0,0 +578,21 @@578+ const leases = this.persistence.stores.leases579+ const attempt =580+ inputId === undefined581+ ? undefined582+ : this.writer?.state.inputs.get(inputId)?.attempt583+ if (!leases || inputId === undefined || attempt === undefined) {584+ return undefined585+ }586+ const ttlMs = this.lease?.ttlMs ?? LEASE.ttlMs587+ const renewMs = this.lease?.renewMs ?? LEASE.renewMs588+ const lease = () => ({589+ threadId: this.threadId,590+ inputId,591+ operationId: operation.id,592+ attempt,593+ ownerId: this.hostId,594+ expiresAt: Date.now() + ttlMs,595+ })596+ await leases.acquire(lease())597+ const timer = setInterval(598+ () => void leases.renew(lease()).catch(() => {}),@@ -0,0 +747,21 @@747+ await this.refreshTurnInterrupts(turn.operation)748+ turn.operation.fail('cancelled', new Error('Session closed.'))749+ }750+ const running = [...this.operations.values()].filter(751+ (operation) => !operation.isSettled(),752+ )753+ for (const operation of running) {754+ operation.abortController.abort(755+ options?.recoverable ? SHUTDOWN_REASON : RUN_CANCEL_REASON,756+ )757+ }758+ for (const question of this.questions.values()) {759+ question.reject(new Error('Session closed.'))760+ }761+ this.questions.clear()762+ await Promise.allSettled(763+ running.map((operation) => Promise.resolve(operation)),764+ )765+ // The events from before the close land first, so the next host has766+ // the text of a cut answer.767+ if (options?.recoverable) await this.writer?.flush().catch(() => {})tombeckenham reviewed
@@ -0,0 +1019,21 @@1019+ * After a crash: queue the logged notes that are not in the transcript,1020+ * and note each logged job that no host runs now.1021+ */1022+ protected async recoverBackground(writer: LogWriter) {1023+ const queued = new Set(this.pendingNotes.map((message) => message.id))1024+ for (const [id, note] of writer.state.notes) {1025+ if (queued.has(id)) continue1026+ this.pendingNotes.push({ id, role: 'assistant', content: note })1027+ }1028+ for (const jobId of [...writer.state.jobs]) {1029+ if (this.jobs.has(jobId)) continue1030+ const id = createMessageId()1031+ const note = `Background job ${jobId} stopped when the host restarted.`1032+ this.pendingNotes.push({ id, role: 'assistant', content: note })1033+ // One batch: a crash keeps both records or neither.1034+ await writer.append([1035+ { type: 'harness.note', noteId: id, note },1036+ { type: 'harness.job', jobId, ended: true },1037+ ])1038+ }1039+ if (!this.activeTurn && !this.reverted) await this.flushNotes()@@ -0,0 +54,21 @@54+ ? this.writer.state.revert55+ : revertOf(56+ await this.persistence.stores.metadata?.get(57+ 'harness:revert',58+ this.threadId,59+ ),60+ )61+ await this.loadInterrupted()62+ // Before recovery: a turn that recovery runs updates this entry.63+ await this.openEntry()64+ if (this.writer) {65+ await this.recoverFromLog(this.writer)66+ return67+ }68+ await this.loadUsage()69+ await this.recoverCrashedTurn()70+ await this.recoverInbox()71+ } catch (error) {72+ // A session that fails to open gives its log view back, so the thread73+ // can open again.74+ this.feed.close()tombeckenham reviewed
@@ -0,0 +111,21 @@111+ ctx.agents.start(migrator, { customer }, { resume: true, wake: true })112+ return `Moving ${customer}.`113+ },114+ }),115+ },116+ }),117+})118+```119+120+Give the host a session log (`stores.log`). See [Durable sessions](./durable-sessions). Without a log, `start` with `resume: true` throws.121+Put each side effect in `harnessContext(ctx).step.do(name, fn)`. The agent code runs again from its start, and a finished step returns its stored value.122+Give each step a name that is the same on every run, and return a JSON value from `fn`.123+124+`harnessContext` comes from `@tanstack/ai-harness`. Outside a run that a session started, `step.do` runs `fn` each time.125+126+What the next host does:127+128+It runs the agent again with the same input. Its `ctx.chat` calls continue from the saved transcript, and its finished tool calls do not run again.129+A step runs at least once. A host can stop after `fn` ran and before the log stored its value. Then the next run calls `fn` again.130+After `durability.maxAttempts` runs (default 10), the run ends `failed` with the code `attempts_exhausted`.131+`host.close()` cancels the run. Only a host that stops without a close (a crash or a kill) leaves the run for the next host.@@ -0,0 +66,21 @@66+ send: (to: string, body: string) => Promise<{ id: string }>67+}68+69+export const notify = durableTool(70+ toolDefinition({71+ name: 'notify',72+ description: 'Email a customer',73+ inputSchema: z.object({ to: z.string(), body: z.string() }),74+ }),75+ async ({ to, body }, { step }) => {76+ const mail = await step.do(`send:${to}`, () => mailer.send(to, body))77+ return { mailId: mail.id }78+ },79+ { replay: 'never' },80+)81+```82+83+After a crash that cuts the call:84+85+`'safe'` (the default): the call runs again. Finished steps return their stored values.86+`'never'`: the model gets a tool error, because nobody knows if the tool finished. The call does not run again. `step` and `append` still work, so the steps and records of the first run stay in the log.@@ -0,0 +74,21 @@74+75+The store is yours, so read your records back from it, for example to rebuild your state when a session opens:76+77+```ts group=harness-session-log78+const entries = await log.read('thread-1')79+const signals = entries.filter((entry) => entry.record.type === 'app.signal')80+console.log(signals.map((entry) => entry.seq))81+```82+83+A reader outside a session that needs a `MessageStore`, for example `reconstructChat`, uses `logMessageStore`. It folds the log with the same `project`:84+85+```ts group=harness-session-log86+import { logMessageStore } from '@tanstack/ai-harness'87+88+const messages = logMessageStore({ store: log, project })89+console.log(await messages.loadThread('thread-1'))90+```91+92+## Tune how text streams into the log93+94+A durable host merges streamed text for `coalesceMs` (default 100) before it appends it. A message start or end, a tool call, and your own records append at once.@@ -590,0 +893,21 @@893+```894+895+The claim is `true` when the statement wrote one row. An index on `until` keeps896+`listExpired` fast.897+898+`memoryPersistence()` includes a memory `workClaims` store. It does not survive a899+restart.900+901+## SessionIndexStore902+903+Your app shows a list of sessions: the title, the owner, the time of the last change,904+and the token totals. Reading every transcript to build that list is slow.905+`SessionIndexStore` keeps one small entry per thread. The index holds no messages.906+The data of each thread stays in the stores that hold it.907+908+```ts909+interface SessionIndexEntry {910+ threadId: string911+ harness?: string // the name of the setup that runs the thread912+ title?: string913+ parentThreadId?: string // a child session, for example `subagent:<runId>`tombeckenham reviewed
@@ -0,0 +257,21 @@257+ timestamp: Date.now(),258+ }259+ let failed: string | undefined260+ for await (const chunk of operation.stream()) {261+ if (262+ FORWARDED.has(chunk.type) &&263+ !('subagentRunId' in chunk && chunk.subagentRunId)264+ ) {265+ yield chunk266+ }267+ if (chunk.type === EventType.RUN_ERROR) failed = chunk.message268+ }269+ if (failed !== undefined) {270+ yield {271+ type: EventType.RUN_ERROR,272+ message: failed,273+ timestamp: Date.now(),274+ }275+ return276+ }277+ yield {@@ -0,0 +46,21 @@46+export const DURABLE_EXECUTE: unique symbol = Symbol(47+ 'tanstack.ai-harness.durable-execute',48+)49+50+/** @internal Steps over `recorded` values, stored with `record`. */51+export function createToolStep(options: {52+ recorded: (name: string) => { found: true; value: unknown } | { found: false }53+ record: (name: string, value: unknown) => Promise<void>54+}) {55+ const used = new Set<string>()56+ const step = {57+ do: async <T>(name: string, fn: () => T | Promise<T>) => {58+ if (used.has(name)) {59+ throw new Error(60+ `step.do: the step name ${JSON.stringify(name)} is already used in this tool call.`,61+ )62+ }63+ used.add(name)64+ const stored = options.recorded(name)65+ // The log holds what an earlier run of this step returned.66+ if (stored.found) return stored.value as T@@ -0,0 +228,21 @@228+ if (!isHarnessDefinition(target)) return remoteHarnessText(target)229+ const harness = target230+ let host = options.host231+ return {232+ kind: 'text',233+ name: 'harness',234+ model: harness.name,235+ inputModalities: inputsOf(harness, options.inputModalities),236+ '~types': TYPES,237+ chatStream: (chatOptions) =>238+ (async function* (): AsyncGenerator<StreamChunk> {239+ host ??= createHarnessHost()240+ const threadId = `${chatOptions.threadId ?? 'default'}:${harness.name}`241+ const runId = chatOptions.runId ?? `harness-${Date.now().toString(36)}`242+ const signal =243+ isRecord(chatOptions.request) &&244+ chatOptions.request.signal instanceof AbortSignal245+ ? chatOptions.request.signal246+ : undefined247+ const session = await host.open(harness, { threadId })248+ const operation = session.prompt(lastUserInput(chatOptions.messages))tombeckenham reviewed
@@ -0,0 +585,21 @@585+ const inputId = createInputId()586+ // A secret (a key or a password) stays out of the inbox. A restart does587+ // not replay an answer, so the inbox never needs it.588+ const isSecret = this.questions.get(questionId)?.secret === true589+ await this.accept(inputId, {590+ op: 'answer',591+ questionId,592+ value: isSecret ? '[secret]' : value,593+ })594+ const question = this.questions.get(questionId)595+ if (!question) return this.reject(inputId, 'unknown_question')596+ let checked: unknown = value597+ if (question.schema !== undefined) {598+ const result = await validateWithStandardSchema(question.schema, value)599+ if (!result.success) {600+ const reason = `Invalid answer: ${result.issues.map((issue) => issue.message).join(', ')}`601+ return this.reject(inputId, reason)602+ }603+ checked = result.data604+ }605+ this.questions.delete(questionId)@@ -0,0 +576,21 @@576+577+ /**578+ * One run of `chain`. Then the steers it never took run as follow-ups,579+ * before the follow-ups that wait, and the next follow-up starts.580+ */581+ protected async executeAgent(582+ operation: AgentRunImpl,583+ chain: AgentChain,584+ start: AgentRunStart,585+ ): Promise<void> {586+ try {587+ await this.runAgentOnce(operation, chain, start)588+ } finally {589+ // After a log failure, another host owns the thread.590+ if (!this.logFailure) {591+ chain.followUps.unshift(592+ ...chain.steers593+ .splice(0)594+ .map((steer) => this.followUpOf(chain, steer)),595+ )596+ this.nextFollowUp(chain)@@ -0,0 +205,21 @@205+ await this.settle({206+ inputId,207+ operationId: operation.id,208+ outcome: error ? 'failed' : 'completed',209+ ...(error ? { error } : {}),210+ }).catch(() => {})211+ }212+ if (error) operation.fail('failed', new Error(error.message))213+ else operation.finish('completed', { text: '' })214+ this.publishFinished(operation)215+ // A steer that came while the reset ran runs as its own turn.216+ this.requeueWaitingSteers()217+ }218+219+ protected async runTurn(turn: QueuedTurn): Promise<void> {220+ // The next turn drops the messages that a revert hides.221+ try {222+ await this.commitRevert()223+ } catch (error) {224+ turn.operation.fail('failed', error)225+ this.publishFinished(turn.operation)github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: maintainer
- @@ -0,0 +150,21 @@150+ })151+ watchers.set(key, watcher)152+ return true153+ } catch {154+ return false155+ }156+ }157+158+ /**159+ * Watch each skill folder. While a folder does not exist, watch its160+ * parent folder, so the skills show as soon as you make the folder.161+ */162+ const watchFolders = () => {163+ for (const dir of dirs) {164+ if (watchers.has(dir)) continue165+ const parentKey = `${dir} (parent)`166+ if (tryWatch(dir, dir, true)) {167+ watchers.get(parentKey)?.close()168+ watchers.delete(parentKey)169+ } else if (!watchers.has(parentKey)) {170+ tryWatch(parentKey, dirname(dir), false)@@ -0,0 +150,21 @@150+ })151+ watchers.set(key, watcher)152+ return true153+ } catch {154+ return false155+ }156+ }157+158+ /**159+ * Watch each skill folder. While a folder does not exist, watch its160+ * parent folder, so the skills show as soon as you make the folder.161+ */162+ const watchFolders = () => {163+ for (const dir of dirs) {164+ if (watchers.has(dir)) continue165+ const parentKey = `${dir} (parent)`166+ if (tryWatch(dir, dir, true)) {167+ watchers.get(parentKey)?.close()168+ watchers.delete(parentKey)169+ } else if (!watchers.has(parentKey)) {170+ tryWatch(parentKey, dirname(dir), false)@@ -0,0 +276,21 @@276+ estimateTokens(render([...kept, skill], 'anthropic')) > limit277+ if (tooLong) break278+ kept.push(skill)279+ }280+ return kept281+ }282+283+ // The sync runs first, so the commands match the folders at the start284+ // of each turn.285+ const middleware: Array<AnyChatMiddleware> = [286+ { name: 'tanstack/skills:sync', setup: () => sync() },287+ withSkills(source, {288+ ...skillsOptions,289+ ...(hasOwnCatalog ? {} : { renderCatalog: shortCatalog }),290+ onLimitExceeded: skillsOptions.onLimitExceeded ?? keepEarlier,291+ }),292+ ]293+294+ return {295+ middleware,296+ commands: {
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: author
- @@ -0,0 +306,21 @@306+307+```ts group=harness-subagents-transcript308+import { defineAgent } from '@tanstack/ai'309+import { createHarnessHost, defineHarness } from '@tanstack/ai-harness'310+import { memoryPersistence } from '@tanstack/ai-persistence'311+import { openaiText } from '@tanstack/ai-openai'312+313+const writer = defineAgent({314+ name: 'writer',315+ description: 'Writes and edits drafts',316+ run: (ctx) => ctx.chat({ adapter: openaiText('gpt-6.1-sol'), stream: false }),317+})318+319+const studio = defineHarness({320+ name: 'acme/studio',321+ adapter: openaiText('gpt-6.1-sol'),322+ subagents: { agents: [writer] },323+})324+325+const host = createHarnessHost({ persistence: memoryPersistence() })326+const session = await host.open(studio, { threadId: 'user-1-thread' })
- @@ -0,0 +23,21 @@23+svelte: @tanstack/ai-acp24+preact: @tanstack/ai-acp25+angular: @tanstack/ai-acp26+octane: @tanstack/ai-acp27+vanilla: @tanstack/ai-acp28+29+<!-- ::end:tabs -->30+31+## 2. Serve the harness32+33+Make a script that the editor starts:34+35+```ts group=harness-acp36+import { serveAcp } from '@tanstack/ai-acp/agent'37+import { createHarnessHost, defineHarness } from '@tanstack/ai-harness'38+import { openaiText } from '@tanstack/ai-openai'39+import { memoryPersistence } from '@tanstack/ai-persistence'40+41+export const assistant = defineHarness({42+ name: 'acme/assistant',43+ adapter: openaiText('gpt-6.1-sol'),@@ -0,0 +205,21 @@205+ */206+export function createAcpAgent(options: AcpAgentOptions): AgentApp {207+ const { host, harness } = options208+ /** The ids of the sessions that this agent opened. */209+ const opened = new Set<string>()210+ /** The last pump of each session. The pumps of one session run in order. */211+ const tails = new Map<string, Promise<void>>()212+213+ // The host gives back the live session of a thread, or opens it again after214+ // it closed, so the agent keeps no session objects.215+ const live = (sessionId: string) =>216+ host.open(harness, { threadId: sessionId })217+218+ /** The session of an id that this agent or the session index knows. */219+ const known = async (sessionId: string) => {220+ if (!opened.has(sessionId) && !(await host.sessions.get(sessionId))) {221+ throw RequestError.resourceNotFound(sessionId)222+ }223+ opened.add(sessionId)224+ return live(sessionId)225+ }
AlemTuzlak changed the title
github-actions[bot](GitHub profile, opens in a new tab) added labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelsmerge-conflicts
tombeckenham changed the title
tombeckenham approved these changes
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) added labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: maintainer
AlemTuzlak changed the title
AlemTuzlak changed the title
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelsmerge-conflicts
AlemTuzlak merged this39c1c79
AlemTuzlak closed this
Sign in to join this conversation.
🦋 Changeset detected#
Latest commit: 9192f2b22aba86ae436289b531ff7213c39589fb
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 74 packages
Not sure what this means? Click here to learn what changesets are.
Click here if you're a maintainer who wants to add another changeset to this PR