Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/thread-host-updates.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
"@systemfsoftware/agent": minor
"@systemfsoftware/agent-storage-sql": minor
"@systemfsoftware/agent-storage-postgres": minor
"@systemfsoftware/agent-storage-cloudflare": none
"@systemfsoftware/agent-storage-memory": none
"@systemfsoftware/agent-storage-sqlite": none
"@systemfsoftware/agent-platform-cloudflare": none
"@systemfsoftware/agent-testing": none
"@systemfsoftware/agent-ai-decision": none
"@systemfsoftware/agent-platform-node": none
"@systemfsoftware/agent-pr-review": none
---

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.

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.
17 changes: 17 additions & 0 deletions docs/src/content/docs/guide/threads.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,20 @@ per-Thread quota. Payloads, individual Runs, live work and host storage have [li
`Thread.Store.snapshot` inspects an in-memory conversation; `Thread.toPrompt` turns it into
an Effect AI Prompt. Durable `ThreadStore` and `ThreadReader` expose journal reads instead.
Authorize tenant and Thread access at the host boundary for both.

## Host updates on a durable Thread

`DurableAgentRuntime.appendHostUpdate({ threadId, updateId, update, relatedRunId? })` commits a
`ThreadHostUpdateAppended` record: progress your host wants on the Thread stream, such as a
gate's state or questions waiting for the user. It belongs to the Thread rather than to a Run, so
you can append one while a Run is active or while the Thread is idle. It never starts or wakes a
Run, and the model never sees it.

- `update` is bounded JSON that your host decodes with its own Schema.
- `updateId` makes the call idempotent: repeating it with the same update returns the first
commit's `sequence` with `deduplicated: true`, and reusing it with a different update fails
with `HostUpdateError` reason `conflict`.
- The record's Thread `sequence` and commit time come from its envelope. Readers of the Thread's
canonical records, including live observers, receive it in sequence order.
- Authorize the caller for the Thread before calling. Appending to a Thread that does not exist
yet fails with `ThreadNotMaterialized`.
20 changes: 20 additions & 0 deletions packages/effect-agent/src/durable/DurableAgentRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ import {
type DurableRuntimeFailpointError,
type DurableRuntimeFailpointLocation,
} from './DurableFailpoint'
import type { HostUpdateAppended, HostUpdateError, HostUpdateRequest } from './HostUpdates'
import {
type AgentRegistration,
BindingUnavailable,
Expand All @@ -160,6 +161,7 @@ import {
} from './internal/agent-registration'
import { makeAgentUpdateRuntime, nativeUpdateAccepted } from './internal/agent-updates'
import { inspectForeignDiagnostic, safeUnknownString } from './internal/foreign-diagnostic'
import { makeHostUpdateRuntime } from './internal/host-updates'
import { initialContext, type InitialContextInput } from './internal/initial-context'
import { type JournalMetadata, type JournalRecordEnvelope, makeJournalMetadata } from './internal/journal-metadata'
import { makeMessagingRuntime } from './internal/messaging-host'
Expand Down Expand Up @@ -486,6 +488,7 @@ const decodeBatchIdSync = Schema.decodeSync(BatchId)
* §12 step 2, D4): one reservation per (parent Run, parent Tool Call) pair,
* so a replayed establishment converges on the one existing row (SUB-016).
*/
export { HostUpdateAppended, HostUpdateError, type HostUpdateRequest } from './HostUpdates'
export const childReservationIdFor = (runId: RunId, toolCallId: ToolCallId): ChildReservationId =>
decodeChildReservationIdSync(`subagent-reservation:${runId}:${toolCallId}`)

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

const hostUpdateRuntime = yield* makeHostUpdateRuntime({
deploymentId: config.deploymentId,
producerId: config.producerId,
}).pipe(Effect.provideService(ThreadStore, progressStore))

return DurableAgentRuntime.of({
bindingRegistryKey: yield* withCrypto(
digestJson({
Expand Down Expand Up @@ -12626,6 +12634,7 @@ const make = Effect.fnUntraced(function*(bindings: ReadonlyArray<ResolvedBinding
awaitProgress,
observe,
abort,
appendHostUpdate: hostUpdateRuntime.append,
resolveUnknown,
resolveApproval,
explain,
Expand Down Expand Up @@ -12774,6 +12783,17 @@ export class DurableAgentRuntime extends Context.Service<
ThreadStoreError | ThreadNotMaterialized | OperationDenied
>
readonly abort: (command: AbortCommand) => Effect.Effect<AbortIntent, DurableAbortFailure>
/**
* Trusted host append of a `ThreadHostUpdateAppended` record. Authorize the caller for the
* Thread first; this is never a model capability. It commits under the Thread's progress gate
* whether or not a Run is active, never wakes a Run, and repeats idempotently by `updateId`.
*/
readonly appendHostUpdate: (
request: HostUpdateRequest,
) => Effect.Effect<
HostUpdateAppended,
HostUpdateError | ThreadStoreError | ThreadNotMaterialized | AppendConflict | OwnershipLost
>
readonly resolveUnknown: (
command: UnknownResolutionCommand,
) => Effect.Effect<UnknownResolutionIntent, DurableResolveFailure | OperationDenied>
Expand Down
21 changes: 21 additions & 0 deletions packages/effect-agent/src/durable/HostUpdates.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import * as Schema from 'effect/Schema'

/**
* `validation`: the update is not bounded JSON or the update ID is invalid. `conflict`: the update
* ID was already used on this Thread with a different update. `contention`: the Thread tail kept
* moving and the append did not commit.
*/
export class HostUpdateError
extends Schema.TaggedError<HostUpdateError, { readonly brand: unique symbol }>()('HostUpdateError', {
reason: Schema.Literals(['validation', 'conflict', 'contention']),
message: Schema.String,
})
{}

/** The committed position of a host update; `deduplicated` when an earlier append already wrote it. */
export class HostUpdateAppended extends Schema.Class<HostUpdateAppended, { readonly brand: unique symbol }>(
'HostUpdateAppended',
)({
sequence: Schema.Int.check(Schema.isGreaterThan(0)),
deduplicated: Schema.Boolean,
}) {}
16 changes: 16 additions & 0 deletions packages/effect-agent/src/durable/HostUpdates.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type * as Schema from 'effect/Schema'

import type { RunId, ThreadId } from '../core/Identifiers'

export { HostUpdateAppended, HostUpdateError } from './HostUpdates.schema'

/** One host update for `DurableAgentRuntime.appendHostUpdate`. */
export interface HostUpdateRequest {
readonly threadId: ThreadId
/** Caller-chosen key; repeating it with the same update returns the first commit. */
readonly updateId: string
/** Bounded JSON the host decodes with its own Schema. */
readonly update: Schema.Json
/** Set only when the update concerns a specific Run. */
readonly relatedRunId?: RunId | undefined
}
17 changes: 15 additions & 2 deletions packages/effect-agent/src/durable/Records.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1044,6 +1044,18 @@ export class AgentUpdateEmitted extends Schema.TaggedClass<AgentUpdateEmitted>()
},
) {}

/**
* A host-authored update on the Thread stream, independent of any Run. The envelope carries its
* Thread sequence and commit time; `relatedRunId` is set only when the host names a Run.
*/
export class ThreadHostUpdateAppended extends Schema.TaggedClass<ThreadHostUpdateAppended>(
'@effect-agent/thread/ThreadHostUpdateAppended',
)('ThreadHostUpdateAppended', {
updateId: IdempotencyKey,
update: PersistedJson,
relatedRunId: Schema.optionalKey(RunId),
}) {}

/** Permanent bounded report refusal. Application errors and raw Run dispositions stay private. */
export class WorkerReportRefused extends Schema.TaggedClass<WorkerReportRefused>()(
'WorkerReportRefused',
Expand Down Expand Up @@ -1253,8 +1265,8 @@ export class RunContinuation extends Schema.TaggedClass<RunContinuation>()(
) {}

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

/** Durable fact and execution-command schemas. Unsupported controls fail before execution. */
export const KnownRecordPayload = Schema.Union([
Expand Down Expand Up @@ -1290,6 +1302,7 @@ export const KnownRecordPayload = Schema.Union([
WorkerInputRefused,
WorkerReportPrepared,
AgentUpdateEmitted,
ThreadHostUpdateAppended,
WorkerReportRefused,
PeerMessagePrepared,
SubtreeBudgetReserved,
Expand Down
1 change: 1 addition & 0 deletions packages/effect-agent/src/durable/RunJournal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,7 @@ const PROMPT_TRANSPARENT_TAGS: ReadonlySet<string> = new Set([
'WorkerInputRefused',
'WorkerReportPrepared',
'AgentUpdateEmitted',
'ThreadHostUpdateAppended',
'WorkerReportRefused',
'PeerMessagePrepared',
'SubtreeBudgetReserved',
Expand Down
138 changes: 138 additions & 0 deletions packages/effect-agent/src/durable/internal/host-updates.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import * as Clock from 'effect/Clock'
import * as DateTime from 'effect/DateTime'
import * as Effect from 'effect/Effect'
import * as Option from 'effect/Option'
import * as Schema from 'effect/Schema'

import type { ThreadId } from '../../core/Identifiers'
import { IdempotencyKey } from '../../core/Receipt'
import type { HostUpdateRequest } from '../HostUpdates'
import { HostUpdateAppended, HostUpdateError } from '../HostUpdates.schema'
import {
BatchId,
CanonicalBatch,
type CanonicalRecordEnvelope,
type DeploymentId,
PersistedJson,
type ProducerId,
RecordEnvelope,
RecordId,
ThreadHostUpdateAppended,
} from '../Records'
import {
type AppendConflict,
AppendRequest,
getRecord,
ThreadReader,
ThreadStore,
type ThreadStoreFailure,
ThreadTailRequest,
} from '../ThreadStore'
import { WakeScheduler } from '../WakeScheduler'

const MAX_TAIL_RETRIES = 8

const invalid = () => HostUpdateError.make({ reason: 'validation', message: 'The host update is not bounded JSON' })

const conflicting = () =>
HostUpdateError.make({ reason: 'conflict', message: 'The update ID was already used with a different update' })

const contended = () =>
HostUpdateError.make({ reason: 'contention', message: 'The Thread tail kept moving; the update did not commit' })

const decodeRecord = Schema.decodeUnknownEffect(
Schema.Struct({
updateId: IdempotencyKey,
update: PersistedJson,
relatedRunId: Schema.optionalKey(ThreadHostUpdateAppended.fields.relatedRunId),
}),
)

const isHostUpdate = Schema.is(ThreadHostUpdateAppended)

const recordIdOf = (updateId: IdempotencyKey) => RecordId.make(`host-update:${updateId}`)
const batchIdOf = (updateId: IdempotencyKey) => BatchId.make(`host-update:${updateId}`)

const matches = (existing: CanonicalRecordEnvelope, payload: ThreadHostUpdateAppended) =>
isHostUpdate(existing.record.payload) &&
Schema.toEquivalence(ThreadHostUpdateAppended)(existing.record.payload, payload)

const actualTailOf = (conflict: AppendConflict) =>
Option.fromUndefinedOr(conflict.actualTailSequence).pipe(Option.filter(() => conflict.reason === 'tail'))

/** @internal Appends host-authored Thread updates under the same progress gate as Run writes. */
export const makeHostUpdateRuntime = Effect.fnUntraced(function*(options: {
readonly deploymentId: DeploymentId
readonly producerId: ProducerId
}) {
const store = yield* ThreadStore
const wake = yield* WakeScheduler
const reader = ThreadReader.fromStore(store)

const existing = (threadId: ThreadId, payload: ThreadHostUpdateAppended) =>
getRecord({ threadId, recordId: recordIdOf(payload.updateId) }).pipe(
Effect.provideService(ThreadReader, reader),
Effect.flatMap(Option.match({
onNone: () => Effect.fail(conflicting()),
onSome: (found) =>
matches(found, payload)
? Effect.succeed(HostUpdateAppended.make({ sequence: found.sequence, deduplicated: true }))
: Effect.fail(conflicting()),
})),
)

const commit = (threadId: ThreadId, batch: CanonicalBatch, payload: ThreadHostUpdateAppended) => {
const attempt = (expectedTailSequence: CanonicalRecordEnvelope['sequence'], retries: number): Effect.Effect<
HostUpdateAppended,
HostUpdateError | ThreadStoreFailure
> =>
store.append(AppendRequest.make({ threadId, batch, expectedTailSequence })).pipe(
Effect.map((result) =>
HostUpdateAppended.make({ sequence: result.firstSequence, deduplicated: result.replayed })
),
Effect.catchTag('AppendConflict', (conflict) =>
Option.match(actualTailOf(conflict), {
onNone: () => existing(threadId, payload),
onSome: (tail) => retryAfter(tail, retries),
})),
)

const retryAfter = (tail: CanonicalRecordEnvelope['sequence'], retries: number) =>
retries >= MAX_TAIL_RETRIES ? Effect.fail(contended()) : attempt(tail, retries + 1)

return store.inspectTail(ThreadTailRequest.make({ threadId })).pipe(
Effect.flatMap((tail) => attempt(tail.tailSequence, 0)),
)
}

const append = Effect.fnUntraced(function*(request: HostUpdateRequest) {
const fields = yield* decodeRecord({
updateId: request.updateId,
update: request.update,
...(request.relatedRunId === undefined ? {} : { relatedRunId: request.relatedRunId }),
}).pipe(Effect.mapError(invalid))
const payload = ThreadHostUpdateAppended.make(fields)
const createdAt = DateTime.makeUnsafe(yield* Clock.currentTimeMillis)
const batch = CanonicalBatch.make({
batchId: batchIdOf(payload.updateId),
producerId: options.producerId,
records: [
RecordEnvelope.make({
recordId: recordIdOf(payload.updateId),
family: 'thread',
schemaVersion: 1,
createdAt,
deploymentId: options.deploymentId,
payload,
}),
],
})
const appended = yield* commit(request.threadId, batch, payload)

yield* wake.notify(request.threadId, 'progress')

return appended
})

return { append }
})
1 change: 1 addition & 0 deletions packages/storage-sql/src/SqlCanonicalStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export const RECORD_TAGS: Readonly<Record<CanonicalRecordPayload['_tag'], number
WorkerReportPrepared: 36,
WorkerReportRefused: 37,
WorkerStopRequested: 38,
ThreadHostUpdateAppended: 39,
})

const sameEnvelope = Schema.toEquivalence(EnvelopeFragments)
Expand Down
Loading
Loading