@xandreed/sdk 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +1 -1
  2. package/dist/agent.adapter.d.ts +111 -11
  3. package/dist/agent.adapter.js +80 -34
  4. package/dist/conformance/index.d.ts +2 -0
  5. package/dist/conformance/index.js +1 -0
  6. package/dist/inbox-runner.adapter.d.ts +18 -0
  7. package/dist/inbox-runner.adapter.js +8 -0
  8. package/dist/index.d.ts +34 -1
  9. package/dist/index.js +58 -1
  10. package/dist/task-executor.adapter.d.ts +32 -0
  11. package/dist/task-executor.adapter.js +10 -0
  12. package/dist/task-inbox-runner.adapter.d.ts +11 -0
  13. package/dist/task-inbox-runner.adapter.js +22 -0
  14. package/dist/turn/memory-checkpoint.adapter.d.ts +17 -0
  15. package/dist/turn/memory-checkpoint.adapter.js +62 -0
  16. package/dist/turn/model-call-recorder.adapter.d.ts +9 -0
  17. package/dist/turn/model-call-recorder.adapter.js +93 -0
  18. package/dist/turn/model-call-recorder.entity.d.ts +145 -0
  19. package/dist/turn/model-call-recorder.entity.functions.d.ts +5 -0
  20. package/dist/turn/model-call-recorder.entity.functions.js +4 -0
  21. package/dist/turn/model-call-recorder.entity.js +8 -0
  22. package/dist/turn/tool-registry.conformance.d.ts +61 -0
  23. package/dist/turn/tool-registry.conformance.js +547 -0
  24. package/dist/turn/turn-after-reply.entity.functions.d.ts +9 -0
  25. package/dist/turn/turn-after-reply.entity.functions.js +4 -0
  26. package/dist/turn/turn-lifecycle.usecase.functions.d.ts +135 -0
  27. package/dist/turn/turn-lifecycle.usecase.functions.js +131 -0
  28. package/dist/turn/turn-observation.entity.d.ts +28 -0
  29. package/dist/turn/turn-observation.entity.functions.d.ts +15 -0
  30. package/dist/turn/turn-observation.entity.functions.js +17 -0
  31. package/dist/turn/turn-observation.entity.js +12 -0
  32. package/dist/turn/turn-overflow.entity.d.ts +7 -0
  33. package/dist/turn/turn-overflow.entity.functions.d.ts +11 -0
  34. package/dist/turn/turn-overflow.entity.functions.js +12 -0
  35. package/dist/turn/turn-overflow.entity.js +5 -0
  36. package/dist/turn/turn-phase.entity.d.ts +462 -0
  37. package/dist/turn/turn-phase.entity.functions.d.ts +44 -0
  38. package/dist/turn/turn-phase.entity.functions.js +49 -0
  39. package/dist/turn/turn-phase.entity.js +13 -0
  40. package/dist/turn/turn-run.usecase.functions.d.ts +72 -0
  41. package/dist/turn/turn-run.usecase.functions.js +329 -0
  42. package/dist/turn/turn.adapter.d.ts +26 -0
  43. package/dist/turn/turn.adapter.js +225 -0
  44. package/package.json +10 -4
  45. package/dist/agent.adapter.test.d.ts +0 -1
  46. package/dist/agent.backends.test.d.ts +0 -1
  47. package/dist/agent.golden.test.d.ts +0 -190
  48. package/dist/memory.conformance.test.d.ts +0 -1
  49. package/dist/plugin-stack.test.d.ts +0 -1
  50. package/dist/testing.port.d.ts +0 -16
  51. package/dist/testing.port.js +0 -7
  52. package/dist/turn-composition.test.d.ts +0 -1
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  # @xandreed/sdk
2
2
 
3
- Efferent composable agent framework, 0.13.0. Node 24 or Bun.
3
+ Efferent composable agent framework, 0.15.0. Node 24 or Bun.
4
4
 
5
5
  Documentation: https://github.com/xandreeddev/efferent
@@ -1,15 +1,23 @@
1
1
  import { Context, Effect } from "effect";
2
2
  import type { Scope } from "effect";
3
3
  import { HarnessError } from "@xandreed/core";
4
- import type { Capability, LoopLimits, Plugin, Turn, TurnInput, TurnOutcome, TurnServices } from "@xandreed/core";
5
- /** One plugin instance of an agent: the definition, its options and (optionally) an instance id. */
4
+ import type { Capability, LoopLimits, Plugin, ProcessActivity, SessionLogError, ShutdownOptions, ShutdownReport, Turn, TurnBeginError, TurnError, TurnInput, TurnOutcome, TurnResult, TurnServices } from "@xandreed/core";
5
+ /**
6
+ * One plugin instance of an agent: the definition, its options and (optionally) an instance id.
7
+ *
8
+ * @public
9
+ */
6
10
  export interface AgentPluginEntry {
7
11
  readonly plugin: Plugin;
8
12
  /** Defaults to the plugin id. */
9
13
  readonly id?: string;
10
14
  readonly options?: Readonly<Record<string, unknown>>;
11
15
  }
12
- /** Everything an agent is made of. Swapping a strategy is swapping one entry. */
16
+ /**
17
+ * Everything an agent is made of. Swapping a strategy is swapping one entry.
18
+ *
19
+ * @public
20
+ */
13
21
  export interface AgentConfig {
14
22
  /** Memory log and strategy, tool registry, step loop, and any capability plugins. */
15
23
  readonly plugins: ReadonlyArray<Plugin | AgentPluginEntry>;
@@ -17,7 +25,11 @@ export interface AgentConfig {
17
25
  readonly bindings?: Readonly<Record<string, string>>;
18
26
  /** The host's own tools, views, skills and prompt sections. */
19
27
  readonly capabilities?: ReadonlyArray<Capability>;
20
- /** Process-lifetime host services plugins may require. */
28
+ /**
29
+ * Process-lifetime host services plugins may require. Their trace state
30
+ * is not replayed into turns (`replayableContext`): a parent span, span
31
+ * annotations or `CurrentTraceContent` among them are ignored.
32
+ */
21
33
  readonly services?: Context.Context<never>;
22
34
  /** Keys every turn's services must carry; session plugins may require them. */
23
35
  readonly turnServices?: ReadonlyArray<{
@@ -28,30 +40,118 @@ export interface AgentConfig {
28
40
  /** The prompt-cache key is `<prefix>:<conversation>`; none is sent without a prefix. */
29
41
  readonly cacheKeyPrefix?: string;
30
42
  readonly workspace?: string;
31
- /** Defaults for every run; a turn's policy overrides them. */
43
+ /**
44
+ * Defaults for every run; a turn's policy overrides them. Its loop
45
+ * protection (`degenerate`, `malformedLimit`) is decoded here
46
+ * (`config.limits`), and a run's merged limits again (`turn.limits`).
47
+ */
32
48
  readonly limits?: Partial<LoopLimits>;
33
- /** Input tokens one request may use (system, tool schemas and messages). */
49
+ /**
50
+ * Every run's token budget unless its policy gives one; 64 000 by default.
51
+ * An integer of at least 1, checked here (`config.budget`). It is the
52
+ * target memory compaction keeps each request under (system prompt, tool
53
+ * schemas and messages, estimated), not a provider limit. Memory is given
54
+ * the whole budget at the turn's start, and at each step what the system
55
+ * prompt and tool schemas leave of it (`context.budget` when they leave
56
+ * nothing). The window strategy compacts, spills and drops older turns to
57
+ * fit the budget it is given, and fails with `context.budget` when the
58
+ * current turn alone does not; the summary strategy summarizes after the
59
+ * turn's sealed reply (and, as a safety net, at a run's start) when
60
+ * messages pass its `triggerRatio`; the digester ignores it. A model whose `ModelCatalog` window (less its output cap) is
61
+ * smaller lowers a step's ceiling to it. Each step's `context.built`
62
+ * records it.
63
+ */
34
64
  readonly budgetTokens?: number;
35
65
  /** How deep event reactions may nest before the bus fails the publisher. */
36
66
  readonly maxEventDepth?: number;
67
+ /**
68
+ * Whether runs' spans may carry prompt and response content
69
+ * (`engine.step.input`, `engine.step.output`, the models plugin's
70
+ * `llm.reasoning`) when a policy does not say (`TurnPolicy.captureTraceContent`).
71
+ * Off by default, unless `CurrentTraceContent` is provided where a run
72
+ * starts: around `Agent.turn`, inside `use`, or in the turn's
73
+ * `TurnInput.services` (one in `services` is ignored: set this instead).
74
+ * Hosts own consent, masking and exporter retention.
75
+ */
76
+ readonly captureTraceContent?: boolean;
77
+ /**
78
+ * The keys of a turn's metadata (`NewTurn.meta`, `AdmittedTurn.meta`) its
79
+ * `agent.turn` span carries, as `efferent.meta.<key>`; none by default
80
+ * (see `TurnTraceOptions`).
81
+ */
82
+ readonly spanMeta?: ReadonlyArray<string>;
83
+ /**
84
+ * A graceful shutdown when the scope `Agent.define` ran in closes: before
85
+ * the agent's plugins close (its sessions plugin and its log with them),
86
+ * `Agent.shutdown` runs with these options and waits for it. Without it,
87
+ * closing that scope stops no turn first.
88
+ */
89
+ readonly shutdown?: ShutdownOptions;
37
90
  }
38
91
  /** A defined agent: its graph is built; each turn is composed by the host. */
39
92
  export interface Agent {
40
93
  readonly fingerprint: string;
94
+ /**
95
+ * What this process is busy with (`processActivity`), as the agent's
96
+ * runtime services see it: the `TurnActivity` of a runtime-scoped
97
+ * sessions plugin in its graph (or one in `services`), and the
98
+ * `TaskActivity` of a task runner in `services` (`InProcessTaskRunnerLive`
99
+ * built into them), owner-observed `WaitingInput`, and active `DrainActivity`:
100
+ * an inbox drainer (`InboxDrainLive`) runs the agent, so it is built beside
101
+ * it and never in its runtime, and the `DrainActivity` provided where this
102
+ * is read counts instead (so does `shutdown`'s).
103
+ * Queue storage failures remain SessionLogError. A missing probe counts nothing: a Sessions
104
+ * the host passes only in a turn's services is not seen here (read
105
+ * `processActivity` with the host's own services instead).
106
+ */
107
+ readonly activity: Effect.Effect<ProcessActivity, SessionLogError>;
108
+ /**
109
+ * Stop this agent's turns within a deadline, while its services are open
110
+ * (`shutdownGracefully` over the same runtime services `activity` reads):
111
+ * refuse every new begin (`TurnRefused`, reason `shutdown`), wait for the
112
+ * turns and tasks running, then close the turns still running at the
113
+ * deadline less its reserve as interrupted with `turn.shutdown`
114
+ * (resumable) and wait out the reserve. `options` default to
115
+ * `AgentConfig.shutdown`, else a deadline of `DEFAULT_SHUTDOWN_DEADLINE`.
116
+ * Begins stay refused afterwards: call it when the process is about to
117
+ * stop (a SIGTERM), then stop the host's request fibers and close the
118
+ * agent's scope.
119
+ */
120
+ readonly shutdown: (options?: ShutdownOptions) => Effect.Effect<ShutdownReport>;
41
121
  /**
42
122
  * Run one turn: one the host began (its `TurnWriter`; the host ends it),
43
123
  * or one begun and ended here through the `Sessions` in the turn's
44
- * services. The turn is scoped: its subscriptions and tasks end with it.
124
+ * services. A turn to begin here that cannot begin fails with the refusal
125
+ * itself (`TurnBeginError`: `SessionBusy`, `TurnDuplicate`,
126
+ * `NotResumable`…; match it with `Effect.catchTag`, `harnessCodeOf` gives
127
+ * its code), before anything is opened, run or counted.
128
+ * The turn is scoped: its subscriptions and tasks end with it.
45
129
  * On success, tasks and background subscriptions settle as the scopes
46
130
  * close in dependency order, before the reply is recorded exactly once.
47
131
  * Failures and interruptions record a failed reply and cancel remaining
48
- * scoped work; recorded events are stored before the turn returns. A turn closed
49
- * elsewhere (cancelled, reaped) fails with `turn.closed`. `use` runs in
132
+ * scoped work; recorded events are stored before the turn returns. A turn
133
+ * begun here ends with `turnEndingOf` its exit: its outcome, or failed
134
+ * with the error's code (`turn.failed` for an error without one,
135
+ * `turn.defect`), or interrupted (`turn.interrupted`); on success, a
136
+ * failure to store that end fails the turn, and on failure one is logged.
137
+ * A turn closed
138
+ * elsewhere (cancelled, reaped, its session removed) fails with that
139
+ * `TurnClosed` (stored as `turn.closed`). `use` runs in
50
140
  * the turn's scope with the turn's services (RunContext, TurnEvents,
51
141
  * TurnTasks and the input's `layer`) provided: the same instances the
52
- * tools, policy and subscriptions see.
142
+ * tools, policy and subscriptions see. It returns `use`'s outcome with
143
+ * the turn's usage (every run's provider calls, summed) and, for a turn
144
+ * begun here, `pending`: the inbox items its end left waiting (results
145
+ * delivered while it ran), which the caller drains (`Sessions.drain`).
146
+ * From the moment
147
+ * the turn is admitted it runs under its `agent.turn` span (`traceTurn`),
148
+ * its logs annotated with the turn's ids (`turnAttributes`), and is
149
+ * counted in the `efferent.turns` and `efferent.turn.duration` metrics by
150
+ * its `efferent.outcome`. A turn begun here begins under its own
151
+ * `agent.turn.begin` span beside it (`traceTurnBegin`), which ends with
152
+ * the refusal's code when the turn cannot begin.
53
153
  */
54
- readonly turn: <A = never, E = never, R = never>(input: TurnInput<A, E>, use: (turn: Turn) => Effect.Effect<TurnOutcome, HarnessError, R>) => Effect.Effect<TurnOutcome, HarnessError | E, Exclude<R, A | TurnServices | Scope.Scope>>;
154
+ readonly turn: <A = never, E = never, R = never>(input: TurnInput<A, E>, use: (turn: Turn) => Effect.Effect<TurnOutcome, TurnError, R>) => Effect.Effect<TurnResult, TurnBeginError | TurnError | E, Exclude<R, A | TurnServices | Scope.Scope>>;
55
155
  }
56
156
  export declare const Agent: {
57
157
  define: (config: AgentConfig) => Effect.Effect<Agent, HarnessError, Scope.Scope>;
@@ -1,44 +1,66 @@
1
- import { Context, Effect, Option, Schema } from "effect";
1
+ import { Cause, Clock, Context, Duration, Effect, Exit, Metric, Option, Schema } from "effect";
2
2
  import {
3
- cacheKeyOf,
3
+ CurrentTraceContent,
4
+ DrainActivity,
5
+ WaitingInput,
4
6
  CapabilitiesLive,
7
+ DEFAULT_SHUTDOWN_DEADLINE,
5
8
  Capabilities,
6
9
  ConversationMemory,
7
10
  definePlugin,
8
- guardTurn,
9
11
  harnessDefectsAsFailures,
10
12
  HarnessError,
11
- openTurnTools,
13
+ LoopProtection,
14
+ isBudgetTokens,
15
+ normalizeUserMessage,
16
+ PluginInstanceId,
17
+ processActivity,
18
+ reasonOf,
19
+ replayableContext,
12
20
  SessionEnvironment,
13
21
  Sessions,
22
+ shutdownGracefully,
14
23
  StepLoop,
24
+ TaskActivity,
15
25
  ToolRegistry,
16
26
  RunContext,
17
- settleTurn,
27
+ TurnActivity,
18
28
  TurnEvents,
29
+ TurnShutdown,
19
30
  TurnTasks,
20
- TurnLive,
21
31
  TurnMemory,
22
32
  TurnPrompt,
23
33
  TurnToolbox,
24
- turnOf
34
+ turnAttributes,
35
+ turnEndingOf
25
36
  } from "@xandreed/core";
26
37
  import { activateGraph, graphFingerprint, resolveGraph } from "@xandreed/runtime";
27
- const failure = (code, message) => new HarnessError({ code, message }), missing = (key) => failure("service.missing", `The agent's plugins do not provide ${key}`), entryOf = (item) => ("plugin" in item) ? item : { plugin: item }, isWriter = (turn) => ("admitted" in turn), beginCodes = {
28
- SessionBusy: "session.busy",
29
- TurnDuplicate: "turn.duplicate",
30
- KeyConflict: "turn.key-conflict",
31
- NothingPending: "session.nothing-pending",
32
- TurnRefused: "turn.refused",
33
- SessionMissing: "session.missing",
34
- SessionLogError: "session.log"
35
- }, beginTurn = (context, turn) => required(context, Sessions).pipe(Effect.flatMap((sessions) => sessions.begin(turn.session, {
36
- _tag: "User",
37
- userMessage: turn.userMessage,
38
- runId: turn.runId,
39
- key: turn.key ?? turn.runId,
40
- command: turn.command ?? {}
41
- })), Effect.mapError((error) => error instanceof HarnessError ? error : failure(beginCodes[error._tag], `the turn could not begin (${error._tag}) in session ${turn.session.id}`))), untilClosed = (writer) => (body) => Effect.raceFirst(body, writer.closed.pipe(Effect.flatMap((closed) => Effect.fail(failure("turn.closed", `turn ${closed.turn} was ${closed.reason}`))))), required = (context, tag) => Option.match(Context.getOption(context, tag), { onNone: () => Effect.fail(missing(tag.key)), onSome: Effect.succeed }), provideHostLayer = (layer) => (effect) => Option.match(layer, { onNone: () => effect, onSome: (hostLayer) => effect.pipe(Effect.provide(hostLayer, { local: !0 })) }), hostCapabilities = (capabilities) => definePlugin({
38
+ import { guardTurn, openTurnTools, settleTurn, traceTurn, traceTurnBegin, turnOf } from "./turn/turn-lifecycle.usecase.functions.js";
39
+ import { cacheKeyOf } from "./turn/turn-run.usecase.functions.js";
40
+ import { TurnLive } from "./turn/turn.adapter.js";
41
+ const failure = (code, message) => new HarnessError({ code, message }), missing = (key) => failure("service.missing", `The agent's plugins do not provide ${key}`), turnCount = Metric.counter("efferent.turns", {
42
+ description: "turns run by Agent.turn, by outcome",
43
+ incremental: !0
44
+ }), turnDuration = Metric.timer("efferent.turn.duration", {
45
+ description: "how long each turn Agent.turn ran took, by outcome"
46
+ }), measureTurn = (effect) => Clock.currentTimeMillis.pipe(Effect.flatMap((started) => effect.pipe(Effect.onExit((exit) => Effect.gen(function* () {
47
+ const outcome = { "efferent.outcome": turnEndingOf(exit).reason }, ended = yield* Clock.currentTimeMillis;
48
+ yield* Metric.update(Metric.withAttributes(turnCount, outcome), 1);
49
+ yield* Metric.update(Metric.withAttributes(turnDuration, outcome), Duration.millis(ended - started));
50
+ }))))), entryOf = (item) => ("plugin" in item) ? item : { plugin: item }, isWriter = (turn) => ("admitted" in turn), keyOf = (turn) => turn.key ?? (turn.resumes === void 0 ? turn.runId : `resume:${turn.resumes}`), beginTurn = (context, turn) => Effect.gen(function* () {
51
+ const sessions = yield* required(context, Sessions), userMessage = yield* normalizeUserMessage(turn.userMessage);
52
+ return yield* sessions.begin(turn.session, {
53
+ _tag: "User",
54
+ userMessage,
55
+ runId: turn.runId,
56
+ key: keyOf(turn),
57
+ command: turn.command ?? {},
58
+ ...turn.meta === void 0 ? {} : { meta: turn.meta },
59
+ ...turn.resumes === void 0 ? {} : { resumes: turn.resumes },
60
+ ...turn.takeOver === !0 ? { takeOver: !0 } : {},
61
+ ...turn.timeLimitMs === void 0 ? {} : { timeLimitMs: turn.timeLimitMs }
62
+ });
63
+ }), untilClosed = (writer) => (body) => Effect.raceFirst(body, writer.closed.pipe(Effect.flatMap((closed) => Effect.fail(closed)))), required = (context, tag) => Option.match(Context.getOption(context, tag), { onNone: () => Effect.fail(missing(tag.key)), onSome: Effect.succeed }), provideHostLayer = (layer) => (effect) => Option.match(layer, { onNone: () => effect, onSome: (hostLayer) => effect.pipe(Effect.provide(hostLayer, { local: !0 })) }), hostCapabilities = (capabilities) => definePlugin({
42
64
  id: "@xandreed/sdk/host-contributions",
43
65
  version: "1",
44
66
  scope: "runtime",
@@ -47,25 +69,34 @@ const failure = (code, message) => new HarnessError({ code, message }), missing
47
69
  provides: [],
48
70
  contributes: [Capabilities],
49
71
  layer: () => CapabilitiesLive(...capabilities)
50
- }), builtInTurnKeys = [RunContext, TurnEvents, TurnTasks, TurnMemory, TurnPrompt, TurnToolbox].map((tag) => tag.key), turnDependentNodes = (graph) => graph.nodes.reduce((late, node) => {
72
+ }), builtInTurnKeys = [RunContext, TurnEvents, TurnTasks, TurnMemory, TurnPrompt, TurnToolbox].map((tag) => tag.key), turnPorts = [ConversationMemory, ToolRegistry, StepLoop].map((tag) => tag.key), turnDependentNodes = (graph) => graph.nodes.reduce((late, node) => {
51
73
  return [...node.plugin.requires, ...node.plugin.optional ?? []].some((key) => builtInTurnKeys.includes(key) || late.some((source) => source.plugin.provides.includes(key) || (source.plugin.contributes ?? []).includes(key))) ? [...late, node] : late;
52
74
  }, []), makeAgent = (config) => Effect.gen(function* () {
75
+ if (config.budgetTokens !== void 0 && !isBudgetTokens(config.budgetTokens))
76
+ return yield* Effect.fail(failure("config.budget", `budgetTokens must be an integer of at least 1, not ${config.budgetTokens}`));
77
+ yield* Schema.decodeUnknownEffect(LoopProtection)(config.limits ?? {}).pipe(Effect.mapError((cause) => new HarnessError({ code: "config.limits", message: "the agent's limits carry a degenerate policy or malformedLimit that does not decode", cause })));
53
78
  const parent = yield* Effect.scope, entries = config.plugins.map(entryOf), hosted = config.capabilities ?? [], host = hostCapabilities(hosted), withHost = hosted.length > 0, plugins = [...withHost ? [host] : [], ...entries.map((entry) => entry.plugin)], harness = {
54
79
  version: 1,
55
80
  plugins: [
56
- ...withHost ? [{ id: host.id, use: host.id }] : [],
57
- ...entries.map((entry) => ({ id: entry.id ?? entry.plugin.id, use: entry.plugin.id, options: { ...entry.options } }))
81
+ ...withHost ? [{ id: PluginInstanceId.make(host.id), use: host.id }] : [],
82
+ ...entries.map((entry) => ({ id: PluginInstanceId.make(entry.id ?? entry.plugin.id), use: entry.plugin.id, options: { ...entry.options } }))
58
83
  ],
59
84
  ...config.bindings === void 0 ? {} : { bindings: { ...config.bindings } },
60
85
  system: config.system ?? ""
61
- }, services = config.services ?? Context.empty(), turnKeys = (config.turnServices ?? []).map((tag) => tag.key), external = [SessionEnvironment.key, ...services.mapUnsafe.keys(), ...turnKeys, ...builtInTurnKeys], graph = yield* resolveGraph(harness, plugins, external), late = turnDependentNodes(graph), invalidLate = late.find((node) => node.plugin.scope === "runtime" || node.plugin.provides.some((key) => [ConversationMemory.key, ToolRegistry.key, StepLoop.key].includes(key)));
86
+ }, services = config.services ?? Context.empty(), turnKeys = (config.turnServices ?? []).map((tag) => tag.key), external = [SessionEnvironment.key, ...services.mapUnsafe.keys(), ...turnKeys, ...builtInTurnKeys], graph = yield* resolveGraph(harness, plugins, external), late = turnDependentNodes(graph), invalidLate = late.find((node) => node.plugin.scope === "runtime" || node.plugin.provides.some((key) => turnPorts.includes(key)));
62
87
  if (invalidLate !== void 0)
63
88
  return yield* Effect.fail(failure("config.graph", `${invalidLate.entry.id}: a plugin requiring turn services must be session-scoped and cannot supply the turn's memory, registry or loop`));
89
+ const unprovided = turnPorts.filter((key) => graph.providers[key] === void 0 && !services.mapUnsafe.has(key) && !turnKeys.includes(key));
90
+ if (unprovided.length > 0)
91
+ return yield* Effect.fail(failure("config.graph", `the agent has no ${unprovided.join(", ")}: no plugin provides it, and neither services nor turnServices carry it`));
64
92
  const beforeTurn = { ...graph, nodes: graph.nodes.filter((node) => !late.includes(node)) }, afterTurn = { ...graph, nodes: late }, workspace = config.workspace ?? ".", seed = Context.add(services, SessionEnvironment, { workspace }), runtime = yield* activateGraph(beforeTurn, "runtime", Context.makeUnsafe(seed.mapUnsafe), parent), perTurn = beforeTurn.nodes.some((node) => node.plugin.scope === "session"), turn = (input, use) => harnessDefectsAsFailures(Effect.scoped(Effect.gen(function* () {
65
93
  const scope = yield* Effect.scope, absent = turnKeys.filter((key) => !input.services.mapUnsafe.has(key));
66
94
  if (absent.length > 0)
67
95
  return yield* Effect.fail(failure("service.missing", `The turn does not provide ${absent.join(", ")}`));
68
- const merged = Context.merge(runtime, input.services), context = perTurn ? yield* activateGraph(beforeTurn, "session", merged, scope) : merged, memory = yield* required(context, ConversationMemory), registry = yield* required(context, ToolRegistry), loop = yield* required(context, StepLoop), own = !isWriter(input.turn), writer = isWriter(input.turn) ? input.turn : yield* beginTurn(context, input.turn), system = input.system ?? config.system, live = {
96
+ const merged = Context.merge(replayableContext(Context.merge(runtime, input.services)), Context.pick(CurrentTraceContent)(input.services)), open = (begin) => Effect.gen(function* () {
97
+ const context = perTurn ? yield* activateGraph(beforeTurn, "session", merged, scope) : merged, memory = yield* required(context, ConversationMemory), registry = yield* required(context, ToolRegistry), loop = yield* required(context, StepLoop), writer = yield* begin(context);
98
+ return { admitted: writer.admitted, writer, context, memory, registry, loop };
99
+ }), requested = input.turn, own = !isWriter(requested), { writer, context, memory, registry, loop } = yield* isWriter(requested) ? open(() => Effect.succeed(requested)) : open((context) => beginTurn(context, requested)).pipe(traceTurnBegin({ session: requested.session.id, runId: requested.runId, origin: "user" })), system = input.system ?? config.system, live = {
69
100
  turn: writer,
70
101
  ...system === void 0 ? {} : { system },
71
102
  ...config.maxEventDepth === void 0 ? {} : { maxEventDepth: config.maxEventDepth }
@@ -73,7 +104,9 @@ const failure = (code, message) => new HarnessError({ code, message }), missing
73
104
  ...config.limits === void 0 ? {} : { limits: config.limits },
74
105
  ...config.budgetTokens === void 0 ? {} : { budgetTokens: config.budgetTokens },
75
106
  cacheKey: Option.orElse(Option.fromNullishOr(input.cacheKey), () => cacheKeyOf(config.cacheKeyPrefix ?? "", writer.admitted.session.id)),
76
- ...input.steering === void 0 ? {} : { steering: input.steering }
107
+ ...input.steering === void 0 ? {} : { steering: input.steering },
108
+ ...input.waiting === void 0 ? {} : { waiting: input.waiting },
109
+ ...config.captureTraceContent === void 0 ? {} : { captureTraceContent: config.captureTraceContent }
77
110
  }, body = Effect.gen(function* () {
78
111
  yield* (yield* TurnMemory).persistMessage;
79
112
  yield* openTurnTools;
@@ -84,11 +117,24 @@ const failure = (code, message) => new HarnessError({ code, message }), missing
84
117
  const activated = yield* activateGraph(afterTurn, "session", Context.merge(context, liveContext), yield* Effect.scope);
85
118
  return yield* effect.pipe(Effect.provide(activated));
86
119
  }));
87
- }), outcome = yield* body.pipe(Effect.tap(() => settleTurn), Effect.scoped, Effect.tap(() => settleTurn), provideHostLayer(Option.fromNullishOr(input.layer)), Effect.tap(() => settleTurn), provideTurnPlugins, guardTurn, Effect.provide(TurnLive(live), { local: !0 }), Effect.provideService(ConversationMemory, memory), Effect.provideService(ToolRegistry, registry), Effect.provideService(StepLoop, loop), Effect.provide(context), untilClosed(writer));
88
- if (own)
89
- yield* writer.end({ reason: outcome.outcome, failure: Option.none() });
90
- return outcome;
91
- })));
92
- return { fingerprint: graphFingerprint(graph), turn };
120
+ });
121
+ return yield* Effect.gen(function* () {
122
+ const exit = yield* body.pipe(Effect.tap(() => settleTurn), Effect.scoped, Effect.tap(() => settleTurn), provideHostLayer(Option.fromNullishOr(input.layer)), Effect.tap(() => settleTurn), provideTurnPlugins, guardTurn, Effect.provide(TurnLive(live), { local: !0 }), Effect.provideService(ConversationMemory, memory), Effect.provideService(ToolRegistry, registry), Effect.provideService(StepLoop, loop), Effect.provide(context), untilClosed(writer), harnessDefectsAsFailures, Effect.exit);
123
+ if (!own)
124
+ return yield* exit;
125
+ if (Exit.isFailure(exit)) {
126
+ yield* writer.end(turnEndingOf(exit)).pipe(Effect.catchTag("TurnClosed", (closed) => Effect.logDebug(`the failed turn's end was not stored: the turn was ${closed.reason}`)), Effect.catch((error) => Effect.logWarning(`the failed turn's end was not stored: ${reasonOf(Cause.fail(error))}`)));
127
+ return yield* Effect.failCause(exit.cause);
128
+ }
129
+ const { pending } = yield* writer.end(turnEndingOf(exit));
130
+ return { ...exit.value, pending };
131
+ }).pipe(Effect.annotateLogs(turnAttributes(writer.admitted)), measureTurn, traceTurn(writer, { spanMeta: config.spanMeta ?? [] }));
132
+ }))), runtimeProbes = (effect) => effect.pipe(Effect.updateContext((current) => {
133
+ const probes = Context.merge(Context.omit(TurnActivity, TaskActivity, TurnShutdown, WaitingInput, DrainActivity)(current), Context.pick(TurnActivity, TaskActivity, TurnShutdown, WaitingInput, DrainActivity)(runtime)), drains = Option.orElse(Context.getOption(runtime, DrainActivity), () => Context.getOption(current, DrainActivity));
134
+ return Option.match(drains, { onNone: () => probes, onSome: (probe) => Context.add(probes, DrainActivity, probe) });
135
+ })), activity = runtimeProbes(processActivity), shutdown = (options) => runtimeProbes(shutdownGracefully(options ?? config.shutdown ?? { deadline: DEFAULT_SHUTDOWN_DEADLINE })).pipe(Effect.tap((report) => report.left.inFlight ? Effect.logWarning(`the agent stopped with ${report.left.openTurns.length + report.left.beginningTurns} turns and ${report.left.runningTasks} tasks still in flight`) : Effect.void)), configured = config.shutdown;
136
+ if (configured !== void 0)
137
+ yield* Effect.addFinalizer(() => shutdown(configured).pipe(Effect.asVoid));
138
+ return { fingerprint: graphFingerprint(graph), activity, shutdown, turn };
93
139
  });
94
140
  export const Agent = { define: makeAgent };
@@ -0,0 +1,2 @@
1
+ export { toolRegistryConformance } from "../turn/tool-registry.conformance.js";
2
+ export type { ToolRegistryLimits } from "../turn/tool-registry.conformance.js";
@@ -0,0 +1 @@
1
+ export { toolRegistryConformance } from "../turn/tool-registry.conformance.js";
@@ -0,0 +1,18 @@
1
+ import { Context, Effect, Layer } from "effect";
2
+ import type { Scope } from "effect";
3
+ import { InboxRunner, Sessions } from "@xandreed/core";
4
+ import type { Turn, TurnError, TurnOutcome, TurnRunner, TurnServices } from "@xandreed/core";
5
+ /**
6
+ * Execute a prebegun inbox or resumed turn through the agent. Build beside
7
+ * the agent and provide the same Sessions that the drainer uses. Its captured
8
+ * Sessions takes precedence over per-turn services. The caller owns the
9
+ * writer's scope and end; this bridge only executes it.
10
+ *
11
+ * By default select skills for the admitted message, run the loop once, and
12
+ * return its outcome and text. A custom use has Agent.turn's turn services.
13
+ * @public
14
+ */
15
+ export declare const agentInboxRunner: (agent: TurnRunner, options: {
16
+ readonly services: Context.Context<never>;
17
+ readonly use?: (turn: Turn) => Effect.Effect<TurnOutcome, TurnError, TurnServices | Scope.Scope>;
18
+ }) => Layer.Layer<InboxRunner, never, Sessions>;
@@ -0,0 +1,8 @@
1
+ import { Context, Effect, Layer, Option } from "effect";
2
+ import { InboxRunner, isTurnError, Sessions } from "@xandreed/core";
3
+ export const agentInboxRunner = (agent, options) => Layer.effect(InboxRunner, Effect.gen(function* () {
4
+ const sessions = yield* Sessions, services = Context.add(options.services, Sessions, sessions), use = options.use ?? ((turn) => turn.tools.select(turn.userMessage).pipe(Effect.andThen(turn.run({})), Effect.map((result) => ({ outcome: result.outcome, reply: result.outcome === "waiting" ? Option.none() : Option.some(result.text) }))));
5
+ return InboxRunner.of({
6
+ run: Effect.fn("inbox_runner.run")((writer) => agent.turn({ turn: writer, services }, use).pipe(Effect.catch((error) => isTurnError(error) ? Effect.fail(error) : Effect.die(error)), Effect.map((result) => ({ outcome: result.outcome, reply: result.reply }))))
7
+ });
8
+ }));
package/dist/index.d.ts CHANGED
@@ -1,3 +1,36 @@
1
- export * from "@xandreed/core";
2
1
  export { Agent } from "./agent.adapter.js";
3
2
  export type { AgentConfig, AgentPluginEntry } from "./agent.adapter.js";
3
+ export { agentInboxRunner } from "./inbox-runner.adapter.js";
4
+ export { taskInboxRunner } from "./task-inbox-runner.adapter.js";
5
+ export { agentTaskExecutor } from "./task-executor.adapter.js";
6
+ export { TurnLive } from "./turn/turn.adapter.js";
7
+ export { cacheKeyOf, runTurnLoop, stepRequestOf } from "./turn/turn-run.usecase.functions.js";
8
+ export type { TurnRunServices } from "./turn/turn-run.usecase.functions.js";
9
+ export { finishTurn, guardTurn, openTurnTools, settleTurn, traceTurn, traceTurnBegin, turnOf, turnTools, } from "./turn/turn-lifecycle.usecase.functions.js";
10
+ export type { TurnBeginTrace, TurnTraceOptions } from "./turn/turn-lifecycle.usecase.functions.js";
11
+ export { ConversationId, mediaFromBase64, mediaFromBytes, RunId, SessionAddress, UserMessage } from "@xandreed/core";
12
+ export type { /** @public */ NewTurn, /** @public */ TurnInput } from "@xandreed/core";
13
+ export type { Turn, TurnOutcome, /** @public */ TurnPolicy, /** @public */ TurnResult } from "@xandreed/core";
14
+ export { SessionLog, SessionLogMemoryLive, Sessions, /** @public */ TurnAdmission, TurnAdmissionOpen, /** @public */ TurnRefused } from "@xandreed/core";
15
+ export {
16
+ /** @public */ defineCapability, definePlugin, definePromptSection,
17
+ /** @public */ defineSkill, defineTool, Failure, Media,
18
+ /** @public */ publishToolProgress, SessionEnvironment,
19
+ /** @public */ ActionPolicy,
20
+ /** @public */ PermissionGrants, } from "@xandreed/core";
21
+ export type { Capability } from "@xandreed/core";
22
+ export { AssistantMessage, defineHostEvent, onEvent, onTool, subscribeAll, TurnEndedData, turnEndedOf, TurnEvent, TurnEvents, } from "@xandreed/core";
23
+ export type { TurnEventOf, TurnEventsService } from "@xandreed/core";
24
+ export { harnessCodeOf,
25
+ /** @public */ HarnessError,
26
+ /** @public */ isHarnessError,
27
+ /** @public */ isTurnError, TurnBeginError, turnBeginCodes, turnEndingOf, } from "@xandreed/core";
28
+ export type { TurnError } from "@xandreed/core";
29
+ export {
30
+ /** @public */ awaitIdle,
31
+ /** @public */ DEFAULT_SHUTDOWN_DEADLINE,
32
+ /** @public */ isShutdownRefusal,
33
+ /** @public */ processActivity,
34
+ /** @public */ shutdownGracefully,
35
+ /** @public */ TurnShutdown, } from "@xandreed/core";
36
+ export type { ShutdownOptions, /** @public */ ShutdownReport } from "@xandreed/core";
package/dist/index.js CHANGED
@@ -1,2 +1,59 @@
1
- export * from "@xandreed/core";
2
1
  export { Agent } from "./agent.adapter.js";
2
+ export { agentInboxRunner } from "./inbox-runner.adapter.js";
3
+ export { taskInboxRunner } from "./task-inbox-runner.adapter.js";
4
+ export { agentTaskExecutor } from "./task-executor.adapter.js";
5
+ export { TurnLive } from "./turn/turn.adapter.js";
6
+ export { cacheKeyOf, runTurnLoop, stepRequestOf } from "./turn/turn-run.usecase.functions.js";
7
+ export {
8
+ finishTurn,
9
+ guardTurn,
10
+ openTurnTools,
11
+ settleTurn,
12
+ traceTurn,
13
+ traceTurnBegin,
14
+ turnOf,
15
+ turnTools
16
+ } from "./turn/turn-lifecycle.usecase.functions.js";
17
+ export { ConversationId, mediaFromBase64, mediaFromBytes, RunId, SessionAddress, UserMessage } from "@xandreed/core";
18
+ export { SessionLog, SessionLogMemoryLive, Sessions, TurnAdmission, TurnAdmissionOpen, TurnRefused } from "@xandreed/core";
19
+ export {
20
+ defineCapability,
21
+ definePlugin,
22
+ definePromptSection,
23
+ defineSkill,
24
+ defineTool,
25
+ Failure,
26
+ Media,
27
+ publishToolProgress,
28
+ SessionEnvironment,
29
+ ActionPolicy,
30
+ PermissionGrants
31
+ } from "@xandreed/core";
32
+ export {
33
+ AssistantMessage,
34
+ defineHostEvent,
35
+ onEvent,
36
+ onTool,
37
+ subscribeAll,
38
+ TurnEndedData,
39
+ turnEndedOf,
40
+ TurnEvent,
41
+ TurnEvents
42
+ } from "@xandreed/core";
43
+ export {
44
+ harnessCodeOf,
45
+ HarnessError,
46
+ isHarnessError,
47
+ isTurnError,
48
+ TurnBeginError,
49
+ turnBeginCodes,
50
+ turnEndingOf
51
+ } from "@xandreed/core";
52
+ export {
53
+ awaitIdle,
54
+ DEFAULT_SHUTDOWN_DEADLINE,
55
+ isShutdownRefusal,
56
+ processActivity,
57
+ shutdownGracefully,
58
+ TurnShutdown
59
+ } from "@xandreed/core";
@@ -0,0 +1,32 @@
1
+ import { Context, Effect, Layer } from "effect";
2
+ import type { Scope } from "effect";
3
+ import { TaskExecutor } from "@xandreed/core";
4
+ import type { TaskView, Turn, TurnError, TurnInput, TurnOutcome, TurnRunner, TurnServices } from "@xandreed/core";
5
+ /** What a task's turn runs once it is composed: a `use` of `Agent.turn`, with the turn's services. */
6
+ type TurnUse = (turn: Turn) => Effect.Effect<TurnOutcome, TurnError, TurnServices | Scope.Scope>;
7
+ /**
8
+ * The `TaskExecutor` that runs a task's turns through an agent (`Agent.turn`,
9
+ * or any `TurnRunner`) with the turn's `services` (its model, the host's
10
+ * per-turn ports) and the `Tasks` it is called with (the tasks plugin's
11
+ * own), so a turn's `start_task` and `task_status` work: the child's one
12
+ * turn with `child` and the parent's
13
+ * reaction to a result with `react`, each by default the turn's skills
14
+ * selected for its message, then one run of the step loop, whose text is the
15
+ * reply. The tasks plugin begins and ends those turns; this only runs them.
16
+ * Build `Tasks` beside the agent, not inside it:
17
+ * `TasksLive(config).pipe(Layer.provide(agentTaskExecutor(agent, { services })))`
18
+ * (a `tasksPlugin` among the agent's own plugins would need the executor
19
+ * before the agent exists).
20
+ *
21
+ * @public
22
+ */
23
+ export declare const agentTaskExecutor: (agent: TurnRunner, options: {
24
+ readonly services: Context.Context<never>;
25
+ /** Optional in-memory steering for both turns; durable input uses their writers' queued steers. */
26
+ readonly steering?: TurnInput["steering"];
27
+ /** The child's turn, given the task it runs. */
28
+ readonly child?: (turn: Turn, task: TaskView) => Effect.Effect<TurnOutcome, TurnError, TurnServices | Scope.Scope>;
29
+ /** The parent's turn that answers the results waiting in its inbox. */
30
+ readonly react?: TurnUse;
31
+ }) => Layer.Layer<TaskExecutor>;
32
+ export {};
@@ -0,0 +1,10 @@
1
+ import { Context, Effect, Layer, Option } from "effect";
2
+ import { isTurnError, TaskExecutor, Tasks } from "@xandreed/core";
3
+ const oneRun = (turn) => turn.tools.select(turn.userMessage).pipe(Effect.andThen(turn.run({})), Effect.map((result) => ({ outcome: result.outcome, reply: result.outcome === "waiting" ? Option.none() : Option.some(result.text) }))), runOn = (agent, services, writer, use, steering, waiting) => Tasks.pipe(Effect.flatMap((tasks) => agent.turn({ turn: writer, services: Context.add(services, Tasks, tasks), ...steering === void 0 ? {} : { steering }, ...waiting === void 0 ? {} : { waiting } }, use)), Effect.catch((error) => isTurnError(error) ? Effect.fail(error) : Effect.die(error)), Effect.map((result) => ({ outcome: result.outcome, reply: result.reply })));
4
+ export const agentTaskExecutor = (agent, options) => {
5
+ const child = options.child ?? oneRun, react = options.react ?? oneRun;
6
+ return Layer.succeed(TaskExecutor, TaskExecutor.of({
7
+ turn: (writer, task, controls) => runOn(agent, options.services, writer, (turn) => child(turn, task), options.steering, controls?.waiting),
8
+ react: (writer) => runOn(agent, options.services, writer, react, options.steering).pipe(Effect.asVoid)
9
+ }));
10
+ };
@@ -0,0 +1,11 @@
1
+ import { Context, Layer } from "effect";
2
+ import { InboxRunner, Sessions, Tasks } from "@xandreed/core";
3
+ /**
4
+ * Route a task child's queued follow-ups through Tasks.execute on the supplied
5
+ * borrowed writer. Other sessions use base. After an acknowledged end, repair
6
+ * task delivery and hand parent notices to the existing task runner. The hook
7
+ * can be skipped on process death; startup Tasks.reconcile repairs the outbox.
8
+ * Build beside the agent with the drainer's own Sessions and Tasks.
9
+ * @public
10
+ */
11
+ export declare const taskInboxRunner: (base: Context.Service.Shape<typeof InboxRunner>) => Layer.Layer<InboxRunner, never, Sessions | Tasks>;
@@ -0,0 +1,22 @@
1
+ import { Context, Effect, Layer, Option } from "effect";
2
+ import { harnessError, InboxRunner, Sessions, Tasks } from "@xandreed/core";
3
+ export const taskInboxRunner = (base) => Layer.effect(InboxRunner, Effect.gen(function* () {
4
+ const sessions = yield* Sessions, tasks = yield* Tasks, sessionOf = (writer) => sessions.get(writer.admitted.session).pipe(Effect.catchTag("SessionMissing", (cause) => Effect.fail(harnessError("task.turn", "The inbox session is unavailable.", cause))));
5
+ return InboxRunner.of({
6
+ run: Effect.fn("task_inbox_runner.run")(function* (writer) {
7
+ return yield* (yield* sessionOf(writer)).header.origin === "task" ? tasks.execute(writer) : base.run(writer);
8
+ }),
9
+ afterEnd: Effect.fn("task_inbox_runner.after_end")(function* (writer, ending) {
10
+ const view = yield* sessionOf(writer);
11
+ if (view.header.origin === "task") {
12
+ const parent = yield* Option.match(view.header.parent, {
13
+ onNone: () => Effect.fail(harnessError("task.turn", "The task session has no parent.")),
14
+ onSome: (lineage) => Effect.succeed({ id: lineage.id, owner: writer.admitted.session.owner })
15
+ });
16
+ yield* tasks.reconcile(parent, { react: !0 }).pipe(Effect.catchTag("SessionMissing", (cause) => Effect.fail(harnessError("task.turn", "The inbox session is unavailable.", cause))));
17
+ }
18
+ if (base.afterEnd !== void 0)
19
+ yield* base.afterEnd(writer, ending);
20
+ })
21
+ });
22
+ }));
@@ -0,0 +1,17 @@
1
+ import { Effect, Option, Schema } from "effect";
2
+ import { MemorySnapshotCandidate } from "@xandreed/core";
3
+ import type { TurnError, TurnWriter } from "@xandreed/core";
4
+ /** The journal-aware bridge is initialized before a custom memory opener can call it. */
5
+ export declare const makeMemoryCheckpoint: (writer: TurnWriter, history: Effect.Effect<readonly {
6
+ readonly session: string & import("effect/Brand").Brand<"ConversationId">;
7
+ readonly seq: number;
8
+ readonly turn: Option.Option<number>;
9
+ readonly kind: string;
10
+ readonly at: number;
11
+ readonly data: {
12
+ readonly [x: string]: Schema.Json;
13
+ };
14
+ }[], TurnError, never>) => Effect.Effect<{
15
+ readonly load: Effect.Effect<Option.Option<MemorySnapshotCandidate>, TurnError>;
16
+ readonly save: (candidate: MemorySnapshotCandidate) => Effect.Effect<void, TurnError>;
17
+ }, never, never>;