Skip to content

Commit ecca79f

Browse files
feat(agent): add a text-completion projection to Agent definitions (#52)
Runs with `completion: 'text'` drop the Definition's completion Tool and then decode the final text as Schema JSON, which streams raw JSON to readers of the live text. Add an optional `textCompletion` projection to `Agent.make` so one Definition serves Runs finished by its completion Tool and Runs finished as plain assistant text. On a `'text'` Run the final assistant text is taken verbatim, rejected when empty, and projected and encoded as the output; a Run that keeps its completion Tool never uses the projection. The per-Run definition copies in the engine and the durable runtime keep `textCompletion` only on `'text'` Runs, the model-visible output contract asks for ordinary text, and the replay digest gains a structural presence marker only when configured. Co-authored-by: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com>
1 parent d2c6238 commit ecca79f

8 files changed

Lines changed: 88 additions & 18 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
"@systemfsoftware/agent": minor
3+
"@systemfsoftware/agent-ai-decision": none
4+
"@systemfsoftware/agent-platform-cloudflare": none
5+
"@systemfsoftware/agent-platform-node": none
6+
"@systemfsoftware/agent-pr-review": none
7+
"@systemfsoftware/agent-storage-cloudflare": none
8+
"@systemfsoftware/agent-storage-memory": none
9+
"@systemfsoftware/agent-storage-postgres": none
10+
"@systemfsoftware/agent-storage-sql": none
11+
"@systemfsoftware/agent-storage-sqlite": none
12+
"@systemfsoftware/agent-testing": none
13+
---
14+
15+
Add `textCompletion` to `Agent.make` so one Definition can complete a `completion: "text"` Run from its final assistant text while other Runs keep the completion Tool. On such a Run the text is projected through `textCompletion`, rejected when empty, and encoded as the output.

‎GLOSSARY.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,13 @@ in its batch. Provider-executed calls may accompany it only with recorded termin
203203
still count toward Run budgets. Ordinary authorization and durability rules apply; the designation
204204
does not guarantee exactly-once effects.
205205

206+
**Text completion**
207+
208+
A Definition's optional `textCompletion` projection, applied when a Run's `completion` mode is
209+
`"text"`. The Run's final assistant text is taken verbatim, projected to the Agent output, and
210+
encoded; an empty or whitespace-only reply is rejected. A Run of a Definition without it decodes
211+
the text through the output Schema instead. A Run that keeps its completion Tool never uses it.
212+
206213
**Step**\
207214
A deterministically named sub-operation within one Durable Tool Call. Its result is
208215
exactly-once-recorded but its external side effect is at-least-once-executed.

‎docs/src/content/docs/guide/per-run-control.md‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@ Attempt, including recovery after an eviction.
1212

1313
`AgentRuntime.run`, `stream` and `start` accept these per-Run options:
1414

15-
| Option | Effect |
16-
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
17-
| `completion` | `"text"` drops the Definition's completion Tool for this Run. The final text is decoded through the Definition's output Schema, as for a Definition without a completion Tool. `"definition"` keeps the default. |
18-
| `contextTokenLimit` | Replaces the policy's `contextTokenLimit` for this Run; it must be a positive integer. Whenever a context limit applies, the compaction pressure check also counts the largest tool result of the most recent Tool batch, so the next Turn has room for a result that size. |
19-
| `toolResultExemption` | `exempt(request)` returns `true` to keep one oversized result inline instead of truncating and offloading it. An exempted result is still bounded by `maxBytes` (a positive integer) and, for durable Runs, by the record limit. |
15+
| Option | Effect |
16+
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
17+
| `completion` | `"text"` drops the Definition's completion Tool for this Run. The final assistant text is taken verbatim and, when the Definition sets `textCompletion`, projected through it; otherwise it decodes through the output Schema as JSON, or is the output directly for `Output.text`, as for a Definition without a completion Tool. `"definition"` keeps the default. |
18+
| `contextTokenLimit` | Replaces the policy's `contextTokenLimit` for this Run; it must be a positive integer. Whenever a context limit applies, the compaction pressure check also counts the largest tool result of the most recent Tool batch, so the next Turn has room for a result that size. |
19+
| `toolResultExemption` | `exempt(request)` returns `true` to keep one oversized result inline instead of truncating and offloading it. An exempted result is still bounded by `maxBytes` (a positive integer) and, for durable Runs, by the record limit. |
2020

2121
The exemption request carries `toolName`, `toolCallId`, `turn`, `isFailure` and the encoded byte
2222
length. It is called only for results larger than `toolResultBounds.maxBytes`.

‎packages/effect-agent/src/core/Agent.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,10 @@ export interface CompletionToolDeclaration<
8282
readonly project: (input: CompletionProjectionInput<Parameters, Result>) => Output
8383
}
8484

85+
export interface TextCompletionProjection<Output> {
86+
readonly project: (text: string) => Output
87+
}
88+
8589
type CompletionToolFor<ToolkitValue extends Toolkit.Any, Output> = {
8690
readonly [Name in keyof ToolkitValue['tools'] & string]:
8791
& CompletionToolDeclaration<
@@ -134,6 +138,7 @@ export interface Definition<
134138
readonly policyOverrides?: Partial<AgentPolicyInput> | undefined
135139
/** When configured, this Tool must succeed to produce final output; ordinary text cannot settle. */
136140
readonly completion?: CompletionToolDeclaration | undefined
141+
readonly textCompletion?: TextCompletionProjection<OutputSchema['Type']> | undefined
137142
readonly runDisposition?: RunDispositionValue | undefined
138143
readonly description?: string | undefined
139144
}
@@ -159,6 +164,7 @@ export interface DefinitionOptions<
159164
readonly toolExposure?: Configuration | undefined
160165
readonly policy?: Partial<AgentPolicyInput> | undefined
161166
readonly completion?: CompletionToolFor<ToolkitValue, OutputSchema['Type']> | undefined
167+
readonly textCompletion?: TextCompletionProjection<OutputSchema['Type']> | undefined
162168
readonly runDisposition?: RunDispositionValue | undefined
163169
readonly description?: string | undefined
164170
}
@@ -477,6 +483,7 @@ export function make(
477483
readonly toolExposure?: Configuration | undefined
478484
readonly policy?: Partial<AgentPolicyInput> | undefined
479485
readonly completion?: CompletionToolDeclaration | undefined
486+
readonly textCompletion?: TextCompletionProjection<unknown> | undefined
480487
readonly runDisposition?: RunDispositionDeclaration<never, Schema.Top> | undefined
481488
readonly description?: string | undefined
482489
},
@@ -508,6 +515,9 @@ export function make(
508515
}),
509516
id: S.decodeSync(AgentId)(id),
510517
completion: options.completion === undefined ? undefined : Object.freeze({ ...options.completion }),
518+
textCompletion: options.textCompletion === undefined
519+
? undefined
520+
: Object.freeze({ ...options.textCompletion }),
511521
runDisposition: options.runDisposition === undefined
512522
? undefined
513523
: Object.freeze({ ...options.runDisposition }),

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

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7993,6 +7993,7 @@ const make = Effect.fnUntraced(function*(bindings: ReadonlyArray<ResolvedBinding
79937993
runStartedAt: runTiming.startedAt,
79947994
durationDeadline: runTiming.deadline,
79957995
...(toolCallAllowance === undefined ? {} : { toolCallAllowance }),
7996+
...(runSettings?.completion === undefined ? {} : { completion: runSettings.completion }),
79967997
...(runSettings?.turnAllowance === undefined ? {} : { turnAllowance: runSettings.turnAllowance }),
79977998
...(runSettings?.contextTokenLimit === undefined
79987999
? {}
@@ -8759,17 +8760,19 @@ const make = Effect.fnUntraced(function*(bindings: ReadonlyArray<ResolvedBinding
87598760
.map((envelope) => envelope.record.payload)
87608761
.find((payload) => payload._tag === 'SubagentLineageRecorded')?.policy
87618762

8762-
const dropCompletion = submission.runSettings?.completion === 'text' &&
8763-
registeredAgent.definition.completion !== undefined
8763+
const textCompletion = submission.runSettings?.completion === 'text'
8764+
const dropCompletion = textCompletion && registeredAgent.definition.completion !== undefined
8765+
const dropTextCompletion = !textCompletion && registeredAgent.definition.textCompletion !== undefined
87648766

8765-
const agent = childPolicy === undefined && !dropCompletion
8767+
const agent = childPolicy === undefined && !dropCompletion && !dropTextCompletion
87668768
? registeredAgent
87678769
: {
87688770
...registeredAgent,
87698771
definition: {
87708772
...registeredAgent.definition,
87718773
...(childPolicy === undefined ? {} : { policy: childPolicy }),
87728774
...(dropCompletion ? { completion: undefined } : {}),
8775+
...(dropTextCompletion ? { textCompletion: undefined } : {}),
87738776
},
87748777
}
87758778

‎packages/effect-agent/src/durable/internal/agent-registration.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,10 @@ const registrationDefinitions = (entry: AgentRegistration): DefinitionDigestInpu
620620
},
621621
}
622622

623+
const withTextCompletion = definition.textCompletion === undefined
624+
? definitions
625+
: { ...definitions, agent: { declaration: definitions.agent, textCompletion: true } }
626+
623627
const exposure = definition.toolExposure
624628

625629
if (
@@ -628,13 +632,13 @@ const registrationDefinitions = (entry: AgentRegistration): DefinitionDigestInpu
628632
(tool) => Context.get(tool.annotations, DiscoveryTool) || Context.get(tool.annotations, PinnedTool),
629633
)
630634
) {
631-
return definitions
635+
return withTextCompletion
632636
}
633637

634638
return {
635-
...definitions,
639+
...withTextCompletion,
636640
agent: {
637-
declaration: definitions.agent,
641+
declaration: withTextCompletion.agent,
638642
toolExposure: {
639643
initialToolNames: exposure === undefined ? null : [...(exposure.initialToolNames ?? [])],
640644
maxTools: exposure?.maxTools ?? 64,

‎packages/effect-agent/src/engine/internal/agent-runtime.ts‎

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3251,14 +3251,17 @@ const withRunDefinitionOverrides = <Definition extends Agent.AnyDefinition, E, R
32513251
definition: Definition,
32523252
options: RunOptions<E, R>,
32533253
): Definition => {
3254-
const dropCompletion = options.completion === 'text' && definition.completion !== undefined
3254+
const textCompletion = options.completion === 'text'
3255+
const dropCompletion = textCompletion && definition.completion !== undefined
3256+
const dropTextCompletion = !textCompletion && definition.textCompletion !== undefined
32553257
const contextTokenLimit = isPositiveSafeInteger(options.contextTokenLimit) ? options.contextTokenLimit : undefined
32563258

3257-
if (!dropCompletion && contextTokenLimit === undefined) return definition
3259+
if (!dropCompletion && !dropTextCompletion && contextTokenLimit === undefined) return definition
32583260

32593261
return Object.freeze({
32603262
...definition,
32613263
...(dropCompletion ? { completion: undefined } : {}),
3264+
...(dropTextCompletion ? { textCompletion: undefined } : {}),
32623265
...(contextTokenLimit === undefined
32633266
? {}
32643267
: { policy: AgentPolicy.make({ ...definition.policy, contextTokenLimit }) }),
@@ -5274,8 +5277,29 @@ const decodeFinalOutput = Effect.fnUntraced(function*<AgentValue extends Agent.A
52745277
): Effect.fn.Return<
52755278
{ readonly encoded: Schema.Json; readonly decoded: Agent.Output<AgentValue> },
52765279
AgentOutputError,
5277-
Agent.OutputSchema<AgentValue>['DecodingServices']
5280+
| Agent.OutputSchema<AgentValue>['DecodingServices']
5281+
| Agent.OutputSchema<AgentValue>['EncodingServices']
52785282
> {
5283+
const textCompletion = agent.definition.textCompletion
5284+
5285+
if (textCompletion !== undefined) {
5286+
if (text.trim().length === 0) {
5287+
return yield* AgentOutputError.make({
5288+
message: 'Agent final text is empty for text completion',
5289+
})
5290+
}
5291+
5292+
const projected = yield* Effect.try({
5293+
try: () => textCompletion.project(text),
5294+
catch: (cause) =>
5295+
AgentOutputError.make({
5296+
message: `Text completion projector failed: ${cause instanceof Error ? cause.message : String(cause)}`,
5297+
}),
5298+
})
5299+
5300+
return yield* encodeOutputCandidate(agent, projected, 'Text completion')
5301+
}
5302+
52795303
const eventJson = isTextOutput(agent.definition.output)
52805304
? text
52815305
: yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Json))(text).pipe(
@@ -5304,13 +5328,14 @@ const decodeFinalOutput = Effect.fnUntraced(function*<AgentValue extends Agent.A
53045328
const encodeOutputCandidate = Effect.fnUntraced(function*<AgentValue extends Agent.Any>(
53055329
agent: AgentValue,
53065330
candidate: unknown,
5331+
subject: string,
53075332
) {
53085333
const encoded = yield* Schema.encodeUnknownEffect<AgentValue['definition']['output']>(
53095334
agent.definition.output,
53105335
)(candidate).pipe(
53115336
Effect.mapError((cause) =>
53125337
AgentOutputError.make({
5313-
message: `Completion Tool output failed Schema encoding: ${cause.message}`,
5338+
message: `${subject} output failed Schema encoding: ${cause.message}`,
53145339
})
53155340
),
53165341
)
@@ -5320,15 +5345,15 @@ const encodeOutputCandidate = Effect.fnUntraced(function*<AgentValue extends Age
53205345
)(encoded).pipe(
53215346
Effect.mapError((cause) =>
53225347
AgentOutputError.make({
5323-
message: `Completion Tool output failed canonical decoding: ${cause.message}`,
5348+
message: `${subject} output failed canonical decoding: ${cause.message}`,
53245349
})
53255350
),
53265351
)
53275352

53285353
const json = yield* Schema.decodeUnknownEffect(Schema.Json)(encoded).pipe(
53295354
Effect.mapError((cause) =>
53305355
AgentOutputError.make({
5331-
message: `Completion Tool output did not encode as durable JSON: ${cause.message}`,
5356+
message: `${subject} output did not encode as durable JSON: ${cause.message}`,
53325357
})
53335358
),
53345359
)
@@ -5383,7 +5408,7 @@ const projectCompletionOutput = Effect.fnUntraced(function*<AgentValue extends A
53835408
}),
53845409
})
53855410

5386-
return yield* encodeOutputCandidate(agent, projected)
5411+
return yield* encodeOutputCandidate(agent, projected, 'Completion Tool')
53875412
})
53885413

53895414
const encodeRunDispositionCandidate = Effect.fnUntraced(function*<

‎packages/effect-agent/src/engine/internal/output-contract.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,12 @@ const renderOutputSchemaContract = (definition: Agent.AnyDefinition): OutputCont
8686
if (definition.completion !== undefined) {
8787
return rendered(requiredCompletionDirective(definition.completion.tool))
8888
}
89+
if (definition.textCompletion !== undefined) {
90+
return rendered(
91+
'Final output contract: write the final reply as ordinary assistant text, without JSON wrapping. ' +
92+
'An empty or whitespace-only reply is not a valid answer.',
93+
)
94+
}
8995
if (isTextOutput(definition.output)) {
9096
return rendered(
9197
'Final output contract: write the final reply as ordinary assistant text, without JSON wrapping. ' +

0 commit comments

Comments
 (0)