Skip to content

Commit fae524e

Browse files
feat(durable): let a host append Thread-scoped updates to the canonical stream (#43)
* feat(browser): JPEG screenshots with a quality setting and a named BrowserSession page type PageScreenshotRequest takes a required PNG or JPEG format; only JPEG carries a quality. BrowserSession.run's page is exported as BrowserSessionPage, because Puppeteer's Node entry declares a separate Page class that is not assignable to the browser build's. * docs(changeset): mark the required screenshot format as breaking * feat(browser): run BrowserSessions on the Browser Run binding alone REST credentials move to an optional lifecycle option. Without them, close sends the browser's own close command and reports unconfirmed cleanup, and read-only Live View fails closed with live-view-requires-rest-credentials. close now returns the cleanup it can prove. * feat(browser): add the PageInspection port and its Browser Sessions adapter One stateful pass per session: listeners attach before navigation and record console and page errors, failed requests and error responses past caller ignore rules; readiness waits on a page function and network idle; one JSON script; named-viewport screenshots; document status, a response header, the landed URL and timings. A pass that never reaches the page returns PageInspectionNotRun. * fix(browser): refuse a disallowed landing origin before readiness runs page functions * docs(durable): name the host requests that carry runStartedAtMillis * feat(durable): let a host append Thread-scoped updates to the canonical stream A new ThreadHostUpdateAppended record (format @7) carries bounded host JSON on the Thread, independent of any Run. appendHostUpdate commits it under the Thread's progress gate, retries tail conflicts, and is idempotent by updateId. The prompt fold skips it. * chore(changeset): list every package and state the format boundary precisely * fix(durable): export the host update request, result and error types --------- Co-authored-by: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com>
1 parent d7bbf39 commit fae524e

10 files changed

Lines changed: 284 additions & 41 deletions

File tree

‎.changeset/thread-host-updates.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
"@systemfsoftware/agent": minor
3+
"@systemfsoftware/agent-storage-sql": minor
4+
"@systemfsoftware/agent-storage-postgres": minor
5+
"@systemfsoftware/agent-storage-cloudflare": none
6+
"@systemfsoftware/agent-storage-memory": none
7+
"@systemfsoftware/agent-storage-sqlite": none
8+
"@systemfsoftware/agent-platform-cloudflare": none
9+
"@systemfsoftware/agent-testing": none
10+
"@systemfsoftware/agent-ai-decision": none
11+
"@systemfsoftware/agent-platform-node": none
12+
"@systemfsoftware/agent-pr-review": none
13+
---
14+
15+
Add `DurableAgentRuntime.appendHostUpdate`, which commits a Thread-scoped `ThreadHostUpdateAppended` record that a host can append while a Run is active or the Thread is idle. It is idempotent by `updateId`, carries bounded JSON, and is skipped by the model's prompt history.
16+
17+
BEHAVIOR CHANGE (breaking): the record format is now `effect-agent/thread@7`. Exports written at `@6` are not imported, and a Postgres store created at `@6` is refused at startup; start from a fresh store.

‎docs/src/content/docs/guide/threads.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,3 +66,20 @@ per-Thread quota. Payloads, individual Runs, live work and host storage have [li
6666
`Thread.Store.snapshot` inspects an in-memory conversation; `Thread.toPrompt` turns it into
6767
an Effect AI Prompt. Durable `ThreadStore` and `ThreadReader` expose journal reads instead.
6868
Authorize tenant and Thread access at the host boundary for both.
69+
70+
## Host updates on a durable Thread
71+
72+
`DurableAgentRuntime.appendHostUpdate({ threadId, updateId, update, relatedRunId? })` commits a
73+
`ThreadHostUpdateAppended` record: progress your host wants on the Thread stream, such as a
74+
gate's state or questions waiting for the user. It belongs to the Thread rather than to a Run, so
75+
you can append one while a Run is active or while the Thread is idle. It never starts or wakes a
76+
Run, and the model never sees it.
77+
78+
- `update` is bounded JSON that your host decodes with its own Schema.
79+
- `updateId` makes the call idempotent: repeating it with the same update returns the first
80+
commit's `sequence` with `deduplicated: true`, and reusing it with a different update fails
81+
with `HostUpdateError` reason `conflict`.
82+
- The record's Thread `sequence` and commit time come from its envelope. Readers of the Thread's
83+
canonical records, including live observers, receive it in sequence order.
84+
- Authorize the caller for the Thread before calling. Appending to a Thread that does not exist
85+
yet fails with `ThreadNotMaterialized`.

‎packages/effect-agent/src/durable/DurableAgentRuntime.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ import {
145145
type DurableRuntimeFailpointError,
146146
type DurableRuntimeFailpointLocation,
147147
} from './DurableFailpoint'
148+
import type { HostUpdateAppended, HostUpdateError, HostUpdateRequest } from './HostUpdates'
148149
import {
149150
type AgentRegistration,
150151
BindingUnavailable,
@@ -160,6 +161,7 @@ import {
160161
} from './internal/agent-registration'
161162
import { makeAgentUpdateRuntime, nativeUpdateAccepted } from './internal/agent-updates'
162163
import { inspectForeignDiagnostic, safeUnknownString } from './internal/foreign-diagnostic'
164+
import { makeHostUpdateRuntime } from './internal/host-updates'
163165
import { initialContext, type InitialContextInput } from './internal/initial-context'
164166
import { type JournalMetadata, type JournalRecordEnvelope, makeJournalMetadata } from './internal/journal-metadata'
165167
import { makeMessagingRuntime } from './internal/messaging-host'
@@ -486,6 +488,7 @@ const decodeBatchIdSync = Schema.decodeSync(BatchId)
486488
* §12 step 2, D4): one reservation per (parent Run, parent Tool Call) pair,
487489
* so a replayed establishment converges on the one existing row (SUB-016).
488490
*/
491+
export { HostUpdateAppended, HostUpdateError, type HostUpdateRequest } from './HostUpdates'
489492
export const childReservationIdFor = (runId: RunId, toolCallId: ToolCallId): ChildReservationId =>
490493
decodeChildReservationIdSync(`subagent-reservation:${runId}:${toolCallId}`)
491494

@@ -12592,6 +12595,11 @@ const make = Effect.fnUntraced(function*(bindings: ReadonlyArray<ResolvedBinding
1259212595
Effect.provideService(ThreadStore, progressStore),
1259312596
)
1259412597

12598+
const hostUpdateRuntime = yield* makeHostUpdateRuntime({
12599+
deploymentId: config.deploymentId,
12600+
producerId: config.producerId,
12601+
}).pipe(Effect.provideService(ThreadStore, progressStore))
12602+
1259512603
return DurableAgentRuntime.of({
1259612604
bindingRegistryKey: yield* withCrypto(
1259712605
digestJson({
@@ -12626,6 +12634,7 @@ const make = Effect.fnUntraced(function*(bindings: ReadonlyArray<ResolvedBinding
1262612634
awaitProgress,
1262712635
observe,
1262812636
abort,
12637+
appendHostUpdate: hostUpdateRuntime.append,
1262912638
resolveUnknown,
1263012639
resolveApproval,
1263112640
explain,
@@ -12774,6 +12783,17 @@ export class DurableAgentRuntime extends Context.Service<
1277412783
ThreadStoreError | ThreadNotMaterialized | OperationDenied
1277512784
>
1277612785
readonly abort: (command: AbortCommand) => Effect.Effect<AbortIntent, DurableAbortFailure>
12786+
/**
12787+
* Trusted host append of a `ThreadHostUpdateAppended` record. Authorize the caller for the
12788+
* Thread first; this is never a model capability. It commits under the Thread's progress gate
12789+
* whether or not a Run is active, never wakes a Run, and repeats idempotently by `updateId`.
12790+
*/
12791+
readonly appendHostUpdate: (
12792+
request: HostUpdateRequest,
12793+
) => Effect.Effect<
12794+
HostUpdateAppended,
12795+
HostUpdateError | ThreadStoreError | ThreadNotMaterialized | AppendConflict | OwnershipLost
12796+
>
1277712797
readonly resolveUnknown: (
1277812798
command: UnknownResolutionCommand,
1277912799
) => Effect.Effect<UnknownResolutionIntent, DurableResolveFailure | OperationDenied>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import * as Schema from 'effect/Schema'
2+
3+
/**
4+
* `validation`: the update is not bounded JSON or the update ID is invalid. `conflict`: the update
5+
* ID was already used on this Thread with a different update. `contention`: the Thread tail kept
6+
* moving and the append did not commit.
7+
*/
8+
export class HostUpdateError
9+
extends Schema.TaggedError<HostUpdateError, { readonly brand: unique symbol }>()('HostUpdateError', {
10+
reason: Schema.Literals(['validation', 'conflict', 'contention']),
11+
message: Schema.String,
12+
})
13+
{}
14+
15+
/** The committed position of a host update; `deduplicated` when an earlier append already wrote it. */
16+
export class HostUpdateAppended extends Schema.Class<HostUpdateAppended, { readonly brand: unique symbol }>(
17+
'HostUpdateAppended',
18+
)({
19+
sequence: Schema.Int.check(Schema.isGreaterThan(0)),
20+
deduplicated: Schema.Boolean,
21+
}) {}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import type * as Schema from 'effect/Schema'
2+
3+
import type { RunId, ThreadId } from '../core/Identifiers'
4+
5+
export { HostUpdateAppended, HostUpdateError } from './HostUpdates.schema'
6+
7+
/** One host update for `DurableAgentRuntime.appendHostUpdate`. */
8+
export interface HostUpdateRequest {
9+
readonly threadId: ThreadId
10+
/** Caller-chosen key; repeating it with the same update returns the first commit. */
11+
readonly updateId: string
12+
/** Bounded JSON the host decodes with its own Schema. */
13+
readonly update: Schema.Json
14+
/** Set only when the update concerns a specific Run. */
15+
readonly relatedRunId?: RunId | undefined
16+
}

‎packages/effect-agent/src/durable/Records.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1044,6 +1044,18 @@ export class AgentUpdateEmitted extends Schema.TaggedClass<AgentUpdateEmitted>()
10441044
},
10451045
) {}
10461046

1047+
/**
1048+
* A host-authored update on the Thread stream, independent of any Run. The envelope carries its
1049+
* Thread sequence and commit time; `relatedRunId` is set only when the host names a Run.
1050+
*/
1051+
export class ThreadHostUpdateAppended extends Schema.TaggedClass<ThreadHostUpdateAppended>(
1052+
'@effect-agent/thread/ThreadHostUpdateAppended',
1053+
)('ThreadHostUpdateAppended', {
1054+
updateId: IdempotencyKey,
1055+
update: PersistedJson,
1056+
relatedRunId: Schema.optionalKey(RunId),
1057+
}) {}
1058+
10471059
/** Permanent bounded report refusal. Application errors and raw Run dispositions stay private. */
10481060
export class WorkerReportRefused extends Schema.TaggedClass<WorkerReportRefused>()(
10491061
'WorkerReportRefused',
@@ -1253,8 +1265,8 @@ export class RunContinuation extends Schema.TaggedClass<RunContinuation>()(
12531265
) {}
12541266

12551267
/** Bump only when the meaning of an existing record changes, independently of SQL layout. */
1256-
export const CURRENT_RECORD_VERSION = 6
1257-
export const CURRENT_RECORD_FORMAT = 'effect-agent/thread@6'
1268+
export const CURRENT_RECORD_VERSION = 7
1269+
export const CURRENT_RECORD_FORMAT = 'effect-agent/thread@7'
12581270

12591271
/** Durable fact and execution-command schemas. Unsupported controls fail before execution. */
12601272
export const KnownRecordPayload = Schema.Union([
@@ -1290,6 +1302,7 @@ export const KnownRecordPayload = Schema.Union([
12901302
WorkerInputRefused,
12911303
WorkerReportPrepared,
12921304
AgentUpdateEmitted,
1305+
ThreadHostUpdateAppended,
12931306
WorkerReportRefused,
12941307
PeerMessagePrepared,
12951308
SubtreeBudgetReserved,

‎packages/effect-agent/src/durable/RunJournal.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,7 @@ const PROMPT_TRANSPARENT_TAGS: ReadonlySet<string> = new Set([
567567
'WorkerInputRefused',
568568
'WorkerReportPrepared',
569569
'AgentUpdateEmitted',
570+
'ThreadHostUpdateAppended',
570571
'WorkerReportRefused',
571572
'PeerMessagePrepared',
572573
'SubtreeBudgetReserved',
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
import * as Clock from 'effect/Clock'
2+
import * as DateTime from 'effect/DateTime'
3+
import * as Effect from 'effect/Effect'
4+
import * as Option from 'effect/Option'
5+
import * as Schema from 'effect/Schema'
6+
7+
import type { ThreadId } from '../../core/Identifiers'
8+
import { IdempotencyKey } from '../../core/Receipt'
9+
import type { HostUpdateRequest } from '../HostUpdates'
10+
import { HostUpdateAppended, HostUpdateError } from '../HostUpdates.schema'
11+
import {
12+
BatchId,
13+
CanonicalBatch,
14+
type CanonicalRecordEnvelope,
15+
type DeploymentId,
16+
PersistedJson,
17+
type ProducerId,
18+
RecordEnvelope,
19+
RecordId,
20+
ThreadHostUpdateAppended,
21+
} from '../Records'
22+
import {
23+
type AppendConflict,
24+
AppendRequest,
25+
getRecord,
26+
ThreadReader,
27+
ThreadStore,
28+
type ThreadStoreFailure,
29+
ThreadTailRequest,
30+
} from '../ThreadStore'
31+
import { WakeScheduler } from '../WakeScheduler'
32+
33+
const MAX_TAIL_RETRIES = 8
34+
35+
const invalid = () => HostUpdateError.make({ reason: 'validation', message: 'The host update is not bounded JSON' })
36+
37+
const conflicting = () =>
38+
HostUpdateError.make({ reason: 'conflict', message: 'The update ID was already used with a different update' })
39+
40+
const contended = () =>
41+
HostUpdateError.make({ reason: 'contention', message: 'The Thread tail kept moving; the update did not commit' })
42+
43+
const decodeRecord = Schema.decodeUnknownEffect(
44+
Schema.Struct({
45+
updateId: IdempotencyKey,
46+
update: PersistedJson,
47+
relatedRunId: Schema.optionalKey(ThreadHostUpdateAppended.fields.relatedRunId),
48+
}),
49+
)
50+
51+
const isHostUpdate = Schema.is(ThreadHostUpdateAppended)
52+
53+
const recordIdOf = (updateId: IdempotencyKey) => RecordId.make(`host-update:${updateId}`)
54+
const batchIdOf = (updateId: IdempotencyKey) => BatchId.make(`host-update:${updateId}`)
55+
56+
const matches = (existing: CanonicalRecordEnvelope, payload: ThreadHostUpdateAppended) =>
57+
isHostUpdate(existing.record.payload) &&
58+
Schema.toEquivalence(ThreadHostUpdateAppended)(existing.record.payload, payload)
59+
60+
const actualTailOf = (conflict: AppendConflict) =>
61+
Option.fromUndefinedOr(conflict.actualTailSequence).pipe(Option.filter(() => conflict.reason === 'tail'))
62+
63+
/** @internal Appends host-authored Thread updates under the same progress gate as Run writes. */
64+
export const makeHostUpdateRuntime = Effect.fnUntraced(function*(options: {
65+
readonly deploymentId: DeploymentId
66+
readonly producerId: ProducerId
67+
}) {
68+
const store = yield* ThreadStore
69+
const wake = yield* WakeScheduler
70+
const reader = ThreadReader.fromStore(store)
71+
72+
const existing = (threadId: ThreadId, payload: ThreadHostUpdateAppended) =>
73+
getRecord({ threadId, recordId: recordIdOf(payload.updateId) }).pipe(
74+
Effect.provideService(ThreadReader, reader),
75+
Effect.flatMap(Option.match({
76+
onNone: () => Effect.fail(conflicting()),
77+
onSome: (found) =>
78+
matches(found, payload)
79+
? Effect.succeed(HostUpdateAppended.make({ sequence: found.sequence, deduplicated: true }))
80+
: Effect.fail(conflicting()),
81+
})),
82+
)
83+
84+
const commit = (threadId: ThreadId, batch: CanonicalBatch, payload: ThreadHostUpdateAppended) => {
85+
const attempt = (expectedTailSequence: CanonicalRecordEnvelope['sequence'], retries: number): Effect.Effect<
86+
HostUpdateAppended,
87+
HostUpdateError | ThreadStoreFailure
88+
> =>
89+
store.append(AppendRequest.make({ threadId, batch, expectedTailSequence })).pipe(
90+
Effect.map((result) =>
91+
HostUpdateAppended.make({ sequence: result.firstSequence, deduplicated: result.replayed })
92+
),
93+
Effect.catchTag('AppendConflict', (conflict) =>
94+
Option.match(actualTailOf(conflict), {
95+
onNone: () => existing(threadId, payload),
96+
onSome: (tail) => retryAfter(tail, retries),
97+
})),
98+
)
99+
100+
const retryAfter = (tail: CanonicalRecordEnvelope['sequence'], retries: number) =>
101+
retries >= MAX_TAIL_RETRIES ? Effect.fail(contended()) : attempt(tail, retries + 1)
102+
103+
return store.inspectTail(ThreadTailRequest.make({ threadId })).pipe(
104+
Effect.flatMap((tail) => attempt(tail.tailSequence, 0)),
105+
)
106+
}
107+
108+
const append = Effect.fnUntraced(function*(request: HostUpdateRequest) {
109+
const fields = yield* decodeRecord({
110+
updateId: request.updateId,
111+
update: request.update,
112+
...(request.relatedRunId === undefined ? {} : { relatedRunId: request.relatedRunId }),
113+
}).pipe(Effect.mapError(invalid))
114+
const payload = ThreadHostUpdateAppended.make(fields)
115+
const createdAt = DateTime.makeUnsafe(yield* Clock.currentTimeMillis)
116+
const batch = CanonicalBatch.make({
117+
batchId: batchIdOf(payload.updateId),
118+
producerId: options.producerId,
119+
records: [
120+
RecordEnvelope.make({
121+
recordId: recordIdOf(payload.updateId),
122+
family: 'thread',
123+
schemaVersion: 1,
124+
createdAt,
125+
deploymentId: options.deploymentId,
126+
payload,
127+
}),
128+
],
129+
})
130+
const appended = yield* commit(request.threadId, batch, payload)
131+
132+
yield* wake.notify(request.threadId, 'progress')
133+
134+
return appended
135+
})
136+
137+
return { append }
138+
})

‎packages/storage-sql/src/SqlCanonicalStorage.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ export const RECORD_TAGS: Readonly<Record<CanonicalRecordPayload['_tag'], number
7373
WorkerReportPrepared: 36,
7474
WorkerReportRefused: 37,
7575
WorkerStopRequested: 38,
76+
ThreadHostUpdateAppended: 39,
7677
})
7778

7879
const sameEnvelope = Schema.toEquivalence(EnvelopeFragments)

0 commit comments

Comments
 (0)