experimental-ash 0.48.0 → 0.49.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.
- package/CHANGELOG.md +11 -0
- package/dist/docs/internals/context.md +6 -12
- package/dist/docs/internals/hooks.md +15 -74
- package/dist/docs/internals/mechanical-invariants.md +3 -4
- package/dist/docs/internals/message-runtime.md +2 -3
- package/dist/docs/public/advanced/hooks.mdx +39 -76
- package/dist/docs/public/advanced/project-layout.md +1 -2
- package/dist/src/compiler/manifest.d.ts +1 -1
- package/dist/src/compiler/normalize-hook.d.ts +4 -4
- package/dist/src/context/hook-lifecycle.d.ts +1 -46
- package/dist/src/context/hook-lifecycle.js +1 -1
- package/dist/src/context/keys.d.ts +0 -9
- package/dist/src/context/keys.js +1 -1
- package/dist/src/execution/create-session-step.d.ts +3 -4
- package/dist/src/execution/create-session-step.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-step.d.ts +2 -3
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/durable-session-store.d.ts +24 -24
- package/dist/src/execution/durable-session-store.js +1 -1
- package/dist/src/execution/turn-workflow.d.ts +4 -5
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.d.ts +1 -1
- package/dist/src/execution/workflow-steps.d.ts +1 -3
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/step-hooks.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/packages/ash-scaffold/src/channels.js +1 -1
- package/dist/src/public/channels/discord/discordChannel.js +1 -1
- package/dist/src/public/channels/discord/inbound.d.ts +0 -3
- package/dist/src/public/channels/discord/inbound.js +1 -1
- package/dist/src/public/channels/discord/index.d.ts +1 -1
- package/dist/src/public/channels/discord/index.js +1 -1
- package/dist/src/public/channels/slack/inbound.d.ts +4 -13
- package/dist/src/public/channels/slack/inbound.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/channels/teams/inbound.d.ts +0 -3
- package/dist/src/public/channels/teams/inbound.js +2 -2
- package/dist/src/public/channels/teams/index.d.ts +1 -1
- package/dist/src/public/channels/teams/index.js +1 -1
- package/dist/src/public/channels/teams/teamsChannel.js +1 -1
- package/dist/src/public/channels/telegram/inbound.d.ts +0 -3
- package/dist/src/public/channels/telegram/inbound.js +1 -1
- package/dist/src/public/channels/telegram/index.d.ts +1 -1
- package/dist/src/public/channels/telegram/index.js +1 -1
- package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
- package/dist/src/public/channels/twilio/inbound.d.ts +0 -3
- package/dist/src/public/channels/twilio/inbound.js +1 -1
- package/dist/src/public/channels/twilio/twilioChannel.js +1 -1
- package/dist/src/public/definitions/hook.d.ts +6 -22
- package/dist/src/public/hooks/index.d.ts +4 -5
- package/dist/src/runtime/graph.d.ts +2 -3
- package/dist/src/runtime/hooks/registry.d.ts +5 -20
- package/dist/src/runtime/hooks/registry.js +1 -1
- package/dist/src/runtime/resolve-hook.d.ts +2 -2
- package/dist/src/runtime/resolve-hook.js +1 -1
- package/dist/src/runtime/types.d.ts +3 -9
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# experimental-ash
|
|
2
2
|
|
|
3
|
+
## 0.49.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 72cd8be: Channels now deliver their inbound `<*_context>` block as a dedicated session-context entry instead of prepending it onto the user's turn message. This applies to Slack, Teams, Discord, Telegram, and Twilio so the model sees the actor/channel metadata as its own message ahead of the user text, and the user turn stays clean. The unused `prependTeamsContext`, `prependDiscordContext`, and `prependTelegramContext` helpers are removed from the public API; use the corresponding `format*ContextBlock` functions if you need to render a block yourself.
|
|
8
|
+
- a703ebb: Remove lifecycle hooks (`lifecycle.session`, `lifecycle.turn`) from the hook system. Hooks now only support stream-event subscribers (`events`). The `LifecycleHook`, `LifecycleHooks` types and `SessionPreparedKey` context key are removed. The `HookDefinition` interface no longer accepts a `lifecycle` field.
|
|
9
|
+
|
|
10
|
+
### Patch Changes
|
|
11
|
+
|
|
12
|
+
- ce09ade: Carry durable session snapshots through Workflow step results and remove `ash.session` write plumbing from current runs. The `ash.session` stream remains only as a legacy read fallback for old stream-backed handles.
|
|
13
|
+
|
|
3
14
|
## 0.48.0
|
|
4
15
|
|
|
5
16
|
### Minor Changes
|
|
@@ -45,7 +45,6 @@ Set by the runtime entry point. Serialized at `"use step"` boundaries via their
|
|
|
45
45
|
| `ParentSessionKey` | `SessionParent` |
|
|
46
46
|
| `ChannelKey` | `Channel` |
|
|
47
47
|
| `BundleKey` | `CompiledBundle` |
|
|
48
|
-
| `SessionPreparedKey` | `boolean` |
|
|
49
48
|
|
|
50
49
|
## Virtual Keys
|
|
51
50
|
|
|
@@ -77,17 +76,12 @@ Framework providers use a superset `FrameworkContextProvider` that also receives
|
|
|
77
76
|
4. Run the callback inside `contextStorage.run(ctx, ...)`
|
|
78
77
|
5. Call framework provider `commit` hooks for provider-owned session state
|
|
79
78
|
|
|
80
|
-
Authored hook
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
`StepInput.modelContext` has two producers. Channels can provide
|
|
87
|
-
ephemeral messages through `SendPayload.modelContext`, and lifecycle
|
|
88
|
-
hooks can provide them through `LifecycleHookResult.modelContext`.
|
|
89
|
-
The merge order is channel first, then `lifecycle.session`, then
|
|
90
|
-
`lifecycle.turn`. The merged messages are visible to the next model
|
|
79
|
+
Authored hook stream-event dispatch runs inside step (4)'s ALS scope.
|
|
80
|
+
Event hooks receive `(event, ctx)`. See [Hooks](./hooks.md) for the
|
|
81
|
+
full pipeline.
|
|
82
|
+
|
|
83
|
+
`StepInput.modelContext` is provided by channels through
|
|
84
|
+
`SendPayload.modelContext`. The messages are visible to the next model
|
|
91
85
|
call only and are never persisted to durable session history.
|
|
92
86
|
|
|
93
87
|
## Channel Context
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
# Hooks
|
|
2
2
|
|
|
3
3
|
Hooks are the first-class extension point for authored agent code that needs
|
|
4
|
-
to
|
|
5
|
-
hooks answer the runtime.
|
|
4
|
+
to observe runtime events. Tools answer the model; hooks answer the runtime.
|
|
6
5
|
|
|
7
6
|
This page explains the discovery → compile → resolve → dispatch pipeline
|
|
8
7
|
and the runtime contract every authored hook handler relies on. The
|
|
@@ -11,8 +10,8 @@ end-user-facing reference lives at
|
|
|
11
10
|
|
|
12
11
|
## Architectural Rationale
|
|
13
12
|
|
|
14
|
-
Plugins and authored agent code need to subscribe to the same
|
|
15
|
-
|
|
13
|
+
Plugins and authored agent code need to subscribe to the same stream
|
|
14
|
+
events. Shipping hooks first closes the gap between "extension authored
|
|
16
15
|
inside the agent" and "extension contributed by a plugin": both flow
|
|
17
16
|
through one runtime registry, one `HookContext`, one set of ordering
|
|
18
17
|
rules.
|
|
@@ -27,20 +26,14 @@ place to look when debugging.
|
|
|
27
26
|
`id`, `auth`, `turn`, and `parent`). `session.auth` is a nested
|
|
28
27
|
`SessionAuth` with `{ current, initiator }`.
|
|
29
28
|
|
|
30
|
-
Lifecycle hooks receive `(ctx)` — a single `HookContext` argument.
|
|
31
29
|
Event hooks receive `(event, ctx)` — event first, context last (omit `ctx` when unused).
|
|
32
|
-
Per-turn `turnId` and `sequence` come from `
|
|
33
|
-
lifecycle hooks, and from `event.data.{turnId, sequence}` for
|
|
30
|
+
Per-turn `turnId` and `sequence` come from `event.data.{turnId, sequence}` for
|
|
34
31
|
stream-event hooks — never duplicated on the context.
|
|
35
32
|
|
|
36
33
|
## Authoring shape
|
|
37
34
|
|
|
38
35
|
```ts
|
|
39
36
|
defineHook({
|
|
40
|
-
lifecycle?: {
|
|
41
|
-
session?: LifecycleHook;
|
|
42
|
-
turn?: LifecycleHook;
|
|
43
|
-
};
|
|
44
37
|
events?: {
|
|
45
38
|
[K in HandleMessageStreamEvent["type"]]?: StreamEventHook<…>;
|
|
46
39
|
"*"?: StreamEventHook<HandleMessageStreamEvent>;
|
|
@@ -48,10 +41,9 @@ defineHook({
|
|
|
48
41
|
});
|
|
49
42
|
```
|
|
50
43
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
in `agent/instructions/` to contribute runtime model messages.
|
|
44
|
+
Hooks are observe-only — they cannot inject model context. Use
|
|
45
|
+
`defineDynamic` + `defineInstructions` in `agent/instructions/` to
|
|
46
|
+
contribute runtime model messages.
|
|
55
47
|
|
|
56
48
|
## Pipeline
|
|
57
49
|
|
|
@@ -69,17 +61,14 @@ compiler performs no per-handler validation — hook handlers are
|
|
|
69
61
|
arbitrary functions and can only be inspected at runtime.
|
|
70
62
|
|
|
71
63
|
Resolve (`src/runtime/resolve-hook.ts`) loads the authored module
|
|
72
|
-
export and reads its
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
time and simply never fire at dispatch time.
|
|
64
|
+
export and reads its `events` map directly. Each declared handler must
|
|
65
|
+
be a function; mismatches throw `ResolveAgentError` so typos surface at
|
|
66
|
+
boot. There is no hardcoded list of valid event types — unknown event
|
|
67
|
+
keys are accepted at resolve time and simply never fire at dispatch time.
|
|
77
68
|
|
|
78
69
|
Registry (`src/runtime/hooks/registry.ts`) builds a
|
|
79
70
|
`RuntimeHookRegistry` per resolved agent node:
|
|
80
71
|
|
|
81
|
-
- `session` — flat ordered array of `lifecycle.session` subscribers.
|
|
82
|
-
- `turn` — flat ordered array of `lifecycle.turn` subscribers.
|
|
83
72
|
- `streamEventsByType` — bucketed map keyed by event type.
|
|
84
73
|
- `streamEventsWildcard` — flat array of `*` subscribers.
|
|
85
74
|
|
|
@@ -89,38 +78,6 @@ the workflow path.
|
|
|
89
78
|
|
|
90
79
|
## Dispatch
|
|
91
80
|
|
|
92
|
-
Lifecycle dispatch lives in `src/context/hook-lifecycle.ts`. The
|
|
93
|
-
workflow runtime entry point (`execution/workflow-steps.ts`) calls
|
|
94
|
-
`runHookLifecycleStep` once per turn, **inside** the active ALS scope
|
|
95
|
-
so hook code can read and write context like every other authored
|
|
96
|
-
function. `runHookLifecycleStep` wraps `dispatchHookLifecycle`, lowers
|
|
97
|
-
a `turn-failed` outcome into a parking `StepResult` (`{ next: null }`
|
|
98
|
-
for conversation mode, `{ next: { done: true, output } }` for task
|
|
99
|
-
mode), and otherwise hands off to the supplied harness step callback
|
|
100
|
-
with the (possibly augmented) input.
|
|
101
|
-
|
|
102
|
-
Dispatch is gated on `getHarnessEmissionState(session).turnId === ""`
|
|
103
|
-
so tool-loop continuations and runtime-action resumes (which are
|
|
104
|
-
continuations of an existing turn) skip the lifecycle stack.
|
|
105
|
-
|
|
106
|
-
Stages, in order:
|
|
107
|
-
|
|
108
|
-
1. **`lifecycle.session`** runs sequentially in registry order, but
|
|
109
|
-
only when `ash.sessionPrepared` is unset. The dispatcher sets the
|
|
110
|
-
flag **before** running the chain so a thrown hook does not retry on
|
|
111
|
-
the next turn — `lifecycle.session` errors are terminal session
|
|
112
|
-
failures (`session.failed`).
|
|
113
|
-
2. **`lifecycle.turn`** runs sequentially. A thrown hook is
|
|
114
|
-
caught here and lowered into a recoverable `turn.failed` cascade
|
|
115
|
-
(`session.started` once → `turn.started` → `message.received` →
|
|
116
|
-
`step.failed` → `turn.failed` → `session.waiting`).
|
|
117
|
-
|
|
118
|
-
If an event hook subscribed to one of the failure-cascade events
|
|
119
|
-
itself throws while the dispatcher is emitting the recoverable
|
|
120
|
-
`turn.failed`, the throw escalates and the runtime emits
|
|
121
|
-
`session.failed` instead. This is the bounded second-order behavior
|
|
122
|
-
when both a `lifecycle.turn` and a `turn.failed` event hook fail.
|
|
123
|
-
|
|
124
81
|
### Stream event dispatch (`handleEvent`)
|
|
125
82
|
|
|
126
83
|
Every stream event passes through one `handleEvent` function
|
|
@@ -151,13 +108,6 @@ right before each model call. See the [event dispatch
|
|
|
151
108
|
doc](../../research/active/unified-event-dispatch.md) for the full
|
|
152
109
|
design.
|
|
153
110
|
|
|
154
|
-
## `SessionPreparedKey`
|
|
155
|
-
|
|
156
|
-
Lives in `src/context/keys.ts`. JSON-safe boolean, no codec. Set
|
|
157
|
-
**before** the `lifecycle.session` chain runs so a thrown hook leaves
|
|
158
|
-
the flag set — the next turn does not retry. Compaction does not clear
|
|
159
|
-
the flag.
|
|
160
|
-
|
|
161
111
|
## Subagent Isolation
|
|
162
112
|
|
|
163
113
|
Subagent hooks are fully isolated by structural construction:
|
|
@@ -175,19 +125,13 @@ The `discover/discover-subagent.ts` path walks each local subagent's
|
|
|
175
125
|
|
|
176
126
|
## Error Containment
|
|
177
127
|
|
|
178
|
-
| Stage
|
|
179
|
-
|
|
|
180
|
-
|
|
|
181
|
-
| `lifecycle.turn` | Caught by dispatcher → recoverable `turn.failed` cascade emitted |
|
|
182
|
-
| Stream-event hooks | Propagated through the emit composer → existing harness error path emits `turn.failed` |
|
|
128
|
+
| Stage | On throw |
|
|
129
|
+
| ------------------ | -------------------------------------------------------------------------------------- |
|
|
130
|
+
| Stream-event hooks | Propagated through the emit composer → existing harness error path emits `turn.failed` |
|
|
183
131
|
|
|
184
132
|
### Full per-turn execution order
|
|
185
133
|
|
|
186
134
|
```
|
|
187
|
-
dispatchHookLifecycle():
|
|
188
|
-
lifecycle.session hooks (once per session, side-effect-only)
|
|
189
|
-
lifecycle.turn hooks (once per turn, side-effect-only)
|
|
190
|
-
|
|
191
135
|
emitTurnPreamble() via handleEvent:
|
|
192
136
|
handleEvent(session.started) → emit, hooks, dynamic tool resolvers
|
|
193
137
|
handleEvent(turn.started) → emit, hooks, dynamic tool resolvers
|
|
@@ -213,9 +157,8 @@ emitStepActions() via handleEvent:
|
|
|
213
157
|
(`src/runtime/hooks/registry.ts` ⇄ `runtime/hooks/registry.test.ts`,
|
|
214
158
|
`src/compiler/normalize-hook.ts` ⇄ `compiler/normalize-hook.test.ts`,
|
|
215
159
|
`src/runtime/resolve-hook.ts` ⇄ `runtime/resolve-hook.test.ts`).
|
|
216
|
-
-
|
|
160
|
+
- Stream-event dispatcher behavior is covered by
|
|
217
161
|
`src/context/hook-lifecycle.integration.test.ts` (synthetic context,
|
|
218
|
-
session/turn lifecycle dispatch, recoverable turn-failed path,
|
|
219
162
|
stream-event fan-out, error propagation).
|
|
220
163
|
- Discovery integration is folded into
|
|
221
164
|
`src/discover/agent.integration.test.ts` (recursive walk,
|
|
@@ -231,8 +174,6 @@ documented expectations:
|
|
|
231
174
|
|
|
232
175
|
- Hook modules never import workflow primitives (`start`, `resumeHook`,
|
|
233
176
|
`createHook`, `getWritable`).
|
|
234
|
-
- Hook return shapes have no `state` field — durable state goes through
|
|
235
|
-
`ctx`.
|
|
236
177
|
- Subagent hooks never read parent ALS context.
|
|
237
178
|
|
|
238
179
|
## Related Pages
|
|
@@ -92,10 +92,9 @@ hooks never read parent ALS context.
|
|
|
92
92
|
Enforcement: rule 27 in `scripts/guard-agents-rules.mjs` fails if a
|
|
93
93
|
`state:` (or `readonly state:`, `state?:`) field is declared on any
|
|
94
94
|
type in `packages/ash/src/public/definitions/hook.ts`. The lint guards
|
|
95
|
-
maintainers from accidentally widening
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
the type does not declare.
|
|
95
|
+
maintainers from accidentally widening hook types into a parallel state
|
|
96
|
+
channel. The TypeScript surface itself rejects authored hooks that
|
|
97
|
+
return any field the type does not declare.
|
|
99
98
|
|
|
100
99
|
The complementary "subagent hooks never read parent ALS context"
|
|
101
100
|
invariant is enforced structurally by the `runStep` ALS-scope split
|
|
@@ -46,9 +46,8 @@ step.completed → turn.completed → session.waiting / session.completed
|
|
|
46
46
|
```
|
|
47
47
|
|
|
48
48
|
Failure variants: `step.failed`, `turn.failed`, `session.failed`.
|
|
49
|
-
A thrown
|
|
50
|
-
|
|
51
|
-
cascade. See [Hooks](./hooks.md).
|
|
49
|
+
A thrown stream-event hook propagates through the emit composer; the
|
|
50
|
+
existing harness error path emits `turn.failed`. See [Hooks](./hooks.md).
|
|
52
51
|
|
|
53
52
|
`message.appended` and `reasoning.appended` carry both delta and cumulative text. `step.completed.data.finishReason` mirrors the model-step outcome (`tool-calls` means the turn continues).
|
|
54
53
|
|
|
@@ -1,28 +1,25 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: "Hooks"
|
|
3
|
-
description: "Subscribe to
|
|
3
|
+
description: "Subscribe to runtime stream events from agent/hooks/."
|
|
4
4
|
url: /hooks
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
-
Hooks are Ash's authored extension points for the
|
|
8
|
-
the runtime event stream.
|
|
7
|
+
Hooks are Ash's authored extension points for the runtime event stream.
|
|
9
8
|
|
|
10
9
|
This page is about `agent/hooks/*.ts` runtime hooks. For the React client hook,
|
|
11
10
|
see [`useAshAgent`](../frontend/use-ash-agent.md).
|
|
12
11
|
|
|
13
|
-
Use a hook when you want to
|
|
14
|
-
|
|
15
|
-
|
|
12
|
+
Use a hook when you want to observe stream events (audit, metrics,
|
|
13
|
+
alerting) without writing a tool, a context provider, or a channel
|
|
14
|
+
adapter handler.
|
|
16
15
|
|
|
17
|
-
<CopyPrompt text="Add an Ash hook to the user's project. Ash hooks live under agent/hooks, use defineHook from experimental-ash/hooks, and can subscribe to
|
|
16
|
+
<CopyPrompt text="Add an Ash hook to the user's project. Ash hooks live under agent/hooks, use defineHook from experimental-ash/hooks, and can subscribe to stream events. Use event handlers for observe-only side effects after events are durably recorded. Inspect existing hooks and agent/lib, choose the smallest hook file and path-derived slug, use defineState only when durable shared state is needed, wrap best-effort side effects so they do not fail sessions accidentally, verify the relevant stream event behavior, and do not commit unless the user asks.">
|
|
18
17
|
Add an Ash hook to the user's project. Ash hooks live under agent/hooks, use defineHook from
|
|
19
|
-
experimental-ash/hooks, and can subscribe to
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
fail sessions accidentally, verify the relevant lifecycle or stream event behavior, and do not
|
|
25
|
-
commit unless the user asks.
|
|
18
|
+
experimental-ash/hooks, and can subscribe to stream events. Use event handlers for observe-only
|
|
19
|
+
side effects after events are durably recorded. Inspect existing hooks and agent/lib, choose the
|
|
20
|
+
smallest hook file and path-derived slug, use defineState only when durable shared state is
|
|
21
|
+
needed, wrap best-effort side effects so they do not fail sessions accidentally, verify the
|
|
22
|
+
relevant stream event behavior, and do not commit unless the user asks.
|
|
26
23
|
</CopyPrompt>
|
|
27
24
|
|
|
28
25
|
## The Main API
|
|
@@ -52,16 +49,27 @@ The slug is the path-relative basename: `agent/hooks/audit.ts` → `"audit"`,
|
|
|
52
49
|
|
|
53
50
|
## Shape
|
|
54
51
|
|
|
55
|
-
A hook file declares
|
|
52
|
+
A hook file declares stream-event subscribers under the `events` map:
|
|
56
53
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
54
|
+
```ts
|
|
55
|
+
defineHook({
|
|
56
|
+
events: {
|
|
57
|
+
"session.started"(event, ctx) {
|
|
58
|
+
/* ... */
|
|
59
|
+
},
|
|
60
|
+
"turn.completed"(event, ctx) {
|
|
61
|
+
/* ... */
|
|
62
|
+
},
|
|
63
|
+
"*"(event, ctx) {
|
|
64
|
+
/* wildcard — fires for every event */
|
|
65
|
+
},
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
```
|
|
61
69
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
70
|
+
Handlers are observe-only — they cannot inject model context. To
|
|
71
|
+
contribute runtime model messages, use `defineDynamic` +
|
|
72
|
+
`defineInstructions` in `agent/instructions/`.
|
|
65
73
|
|
|
66
74
|
Every handler receives the same `HookContext`:
|
|
67
75
|
|
|
@@ -110,48 +118,6 @@ callId }` with `output` typed as the tool's `TOutput`. For connections
|
|
|
110
118
|
it includes `{ output, toolName, connectionToolName, callId }` with
|
|
111
119
|
`output` as `unknown`.
|
|
112
120
|
|
|
113
|
-
## Lifecycle
|
|
114
|
-
|
|
115
|
-
Lifecycle hooks share one signature:
|
|
116
|
-
|
|
117
|
-
```ts
|
|
118
|
-
type LifecycleHook = (ctx: HookContext) => void | Promise<void>;
|
|
119
|
-
```
|
|
120
|
-
|
|
121
|
-
Session and turn metadata are available on `ctx.session`. For example,
|
|
122
|
-
`ctx.session.turn.sequence` gives the current turn sequence number.
|
|
123
|
-
|
|
124
|
-
`lifecycle.session` runs **once per durable session**, before the first
|
|
125
|
-
model turn. `lifecycle.turn` runs **once per fresh delivery** — tool-loop
|
|
126
|
-
continuations and HITL resumes do not re-fire it.
|
|
127
|
-
|
|
128
|
-
Hooks are side-effect-only — they cannot inject model context. To
|
|
129
|
-
contribute runtime model messages, use `defineDynamic` +
|
|
130
|
-
`defineInstructions` in `agent/instructions/`.
|
|
131
|
-
|
|
132
|
-
### Seed durable context
|
|
133
|
-
|
|
134
|
-
```ts
|
|
135
|
-
// agent/hooks/load-profile.ts
|
|
136
|
-
import { defineState } from "experimental-ash/context";
|
|
137
|
-
import { defineHook } from "experimental-ash/hooks";
|
|
138
|
-
import { fetchGithubProfile, type GithubProfile } from "../lib/github";
|
|
139
|
-
|
|
140
|
-
const githubProfile = defineState<GithubProfile | null>("myapp.githubProfile", () => null);
|
|
141
|
-
|
|
142
|
-
export default defineHook({
|
|
143
|
-
lifecycle: {
|
|
144
|
-
async session(ctx) {
|
|
145
|
-
const profile = await fetchGithubProfile(ctx.session.id);
|
|
146
|
-
githubProfile.update(() => profile);
|
|
147
|
-
},
|
|
148
|
-
},
|
|
149
|
-
});
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
The profile is now visible to every tool, provider, and subsequent hook
|
|
153
|
-
through `githubProfile.get()`.
|
|
154
|
-
|
|
155
121
|
## Stream Events
|
|
156
122
|
|
|
157
123
|
Side-effect-only handlers for accepted runtime events. Subscribe by
|
|
@@ -190,11 +156,9 @@ Hooks always run **after** the event is durably recorded — if a hook throws, t
|
|
|
190
156
|
|
|
191
157
|
## Errors
|
|
192
158
|
|
|
193
|
-
| Stage
|
|
194
|
-
|
|
|
195
|
-
| `
|
|
196
|
-
| `lifecycle.turn` | Recoverable turn failure (`turn.failed`). Session keeps living. |
|
|
197
|
-
| `events.*` | Propagates through the emit composer; the existing harness error path emits `turn.failed`. If the hook subscribed to a failure-cascade event also throws, the runtime escalates to `session.failed`. |
|
|
159
|
+
| Stage | On throw |
|
|
160
|
+
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
161
|
+
| `events.*` | Propagates through the emit composer; the existing harness error path emits `turn.failed`. If the hook subscribed to a failure-cascade event also throws, the runtime escalates to `session.failed`. |
|
|
198
162
|
|
|
199
163
|
If you want belt-and-suspenders semantics inside a hook, wrap the body
|
|
200
164
|
in `try`/`catch` — Ash treats a thrown hook as a real failure.
|
|
@@ -208,13 +172,12 @@ context.
|
|
|
208
172
|
|
|
209
173
|
## When to use a hook vs a tool vs a provider
|
|
210
174
|
|
|
211
|
-
| Need
|
|
212
|
-
|
|
|
213
|
-
|
|
|
214
|
-
|
|
|
215
|
-
|
|
|
216
|
-
|
|
|
217
|
-
| Subscribe to platform-specific events | a channel adapter handler |
|
|
175
|
+
| Need | Use |
|
|
176
|
+
| ------------------------------------------------- | -------------------------------------------- |
|
|
177
|
+
| Observe runtime events (audit, metrics, alerting) | `events.<type>` (or channel adapter handler) |
|
|
178
|
+
| Provide structured input to the model on demand | a tool |
|
|
179
|
+
| Make a value available across the entire step | a context provider |
|
|
180
|
+
| Subscribe to platform-specific events | a channel adapter handler |
|
|
218
181
|
|
|
219
182
|
Stream-event hooks and channel adapter event handlers are structurally
|
|
220
183
|
identical — choose the channel adapter handler when you are authoring
|
|
@@ -149,8 +149,7 @@ Use:
|
|
|
149
149
|
- `instructions.md` (or `instructions.ts`) for always-on identity and behavior
|
|
150
150
|
- `skills/` for optional procedures the model should load on demand
|
|
151
151
|
- `tools/` for typed business logic and API calls
|
|
152
|
-
- `hooks/` for
|
|
153
|
-
stream-event subscribers
|
|
152
|
+
- `hooks/` for stream-event subscribers
|
|
154
153
|
- `connections/` for external services exposed via MCP (model discovers and calls their tools)
|
|
155
154
|
- `sandbox/` for sandbox overrides and seeded workspace files
|
|
156
155
|
- `channels/` for HTTP or messaging ingress and delivery
|
|
@@ -129,7 +129,7 @@ export interface CompiledDynamicInstructionsDefinition extends ModuleSourceRef {
|
|
|
129
129
|
/**
|
|
130
130
|
* Normalized authored hook entry preserved in the compiled manifest.
|
|
131
131
|
*
|
|
132
|
-
* Hook
|
|
132
|
+
* Hook event handlers are arbitrary functions — there is no static
|
|
133
133
|
* shape the compiler can validate beyond the source ref. Per-handler
|
|
134
134
|
* resolution happens at runtime via {@link resolveHookDefinition}.
|
|
135
135
|
*/
|
|
@@ -4,9 +4,9 @@ import type { CompiledHookDefinition } from "./manifest.js";
|
|
|
4
4
|
* Compiles one authored hook module into the manifest entry stored on
|
|
5
5
|
* the compiled agent node.
|
|
6
6
|
*
|
|
7
|
-
* Hook
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
7
|
+
* Hook event handlers are arbitrary functions and cannot be statically
|
|
8
|
+
* validated at compile time — the normalization step only derives the
|
|
9
|
+
* path-relative slug used for diagnostics and ordering. Per-handler
|
|
10
|
+
* validation lives in the runtime resolver.
|
|
11
11
|
*/
|
|
12
12
|
export declare function compileHookEntry(source: ModuleSourceRef): CompiledHookDefinition;
|
|
@@ -1,45 +1,6 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type { HandleMessageStreamEvent, RuntimeIdentity } from "#protocol/message.js";
|
|
3
|
-
import type { RunMode } from "#shared/run-mode.js";
|
|
1
|
+
import type { HandleMessageStreamEvent } from "#protocol/message.js";
|
|
4
2
|
import type { RuntimeHookRegistry } from "#runtime/hooks/registry.js";
|
|
5
3
|
import type { ContextContainer } from "./container.js";
|
|
6
|
-
/**
|
|
7
|
-
* Outcome of {@link dispatchHookLifecycle}. `proceed` carries the
|
|
8
|
-
* input augmented with merged context. `turn-failed` means a
|
|
9
|
-
* `lifecycle.turn` hook threw; the recoverable `turn.failed` cascade
|
|
10
|
-
* has already been emitted.
|
|
11
|
-
*/
|
|
12
|
-
export type HookLifecycleOutcome = {
|
|
13
|
-
readonly kind: "proceed";
|
|
14
|
-
readonly input: StepInput;
|
|
15
|
-
readonly nextSession: HarnessSession;
|
|
16
|
-
} | {
|
|
17
|
-
readonly kind: "turn-failed";
|
|
18
|
-
readonly message: string;
|
|
19
|
-
readonly nextSession: HarnessSession;
|
|
20
|
-
};
|
|
21
|
-
export interface DispatchHookLifecycleInput {
|
|
22
|
-
readonly ctx: ContextContainer;
|
|
23
|
-
readonly registry: RuntimeHookRegistry;
|
|
24
|
-
readonly session: HarnessSession;
|
|
25
|
-
readonly input: StepInput;
|
|
26
|
-
readonly emit: HarnessEmitFn;
|
|
27
|
-
readonly mode: RunMode;
|
|
28
|
-
readonly runtimeIdentity?: RuntimeIdentity;
|
|
29
|
-
}
|
|
30
|
-
/**
|
|
31
|
-
* Runs the per-turn hook lifecycle inside the active ALS scope.
|
|
32
|
-
*
|
|
33
|
-
* - `lifecycle.session` runs once per session, gated by
|
|
34
|
-
* {@link SessionPreparedKey}. The flag is set **before** the chain
|
|
35
|
-
* runs so a thrown hook does not retry. A throw re-propagates and
|
|
36
|
-
* the runtime escalates to terminal `session.failed`.
|
|
37
|
-
* - `lifecycle.turn` runs once per fresh delivery. Each hook may
|
|
38
|
-
* return `{ context }`; context contributions are
|
|
39
|
-
* concatenated in registry order. A thrown hook emits the recoverable
|
|
40
|
-
* `turn.failed` cascade and returns `kind: "turn-failed"`.
|
|
41
|
-
*/
|
|
42
|
-
export declare function dispatchHookLifecycle(input: DispatchHookLifecycleInput): Promise<HookLifecycleOutcome>;
|
|
43
4
|
/**
|
|
44
5
|
* Fans one runtime stream event out to every matching subscriber.
|
|
45
6
|
* Errors propagate — harness error paths convert them into the
|
|
@@ -51,9 +12,3 @@ export declare function dispatchStreamEventHooks(input: {
|
|
|
51
12
|
readonly registry: RuntimeHookRegistry;
|
|
52
13
|
readonly event: HandleMessageStreamEvent;
|
|
53
14
|
}): Promise<void>;
|
|
54
|
-
/**
|
|
55
|
-
* Runs the per-turn hook lifecycle, lowers a `turn-failed` outcome
|
|
56
|
-
* into a parking {@link StepResult}, and otherwise hands off to
|
|
57
|
-
* `body` with the (possibly augmented) input.
|
|
58
|
-
*/
|
|
59
|
-
export declare function runHookLifecycleStep(input: DispatchHookLifecycleInput, body: (session: HarnessSession, input: StepInput) => Promise<StepResult>): Promise<StepResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ContinuationTokenKey
|
|
1
|
+
import{ContinuationTokenKey}from"./keys.js";import{getAdapterKind}from"#channel/adapter.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";async function dispatchStreamEventHooks(e){let t=e.registry.streamEventsByType.get(e.event.type)??[],n=e.registry.streamEventsWildcard;if(t.length===0&&n.length===0)return;let r=buildHookContext(e.ctx);for(let n of t)await n.handler(e.event,r);for(let t of n)await t.handler(e.event,r)}function buildHookContext(i){let a=i.require(BundleKey),o=i.get(ChannelKey),s=i.get(ContinuationTokenKey),c=o===void 0?void 0:getAdapterKind(o);return{...buildCallbackContext(),agent:{name:a.resolvedAgent.config.name??`agent`,nodeId:a.nodeId},channel:{kind:c,continuationToken:s}}}export{dispatchStreamEventHooks};
|
|
@@ -47,15 +47,6 @@ export declare const CapabilitiesKey: ContextKey<SessionCapabilities>;
|
|
|
47
47
|
* Optional framework-owned terminal callback metadata for this session.
|
|
48
48
|
*/
|
|
49
49
|
export declare const SessionCallbackKey: ContextKey<SessionCallback>;
|
|
50
|
-
/**
|
|
51
|
-
* Marker durable boolean set by the runtime **before** the
|
|
52
|
-
* `lifecycle.session` hook chain runs. The runtime checks this flag at
|
|
53
|
-
* the top of every turn so the chain never runs twice for the same
|
|
54
|
-
* session — including when one of the hooks throws. A thrown hook is
|
|
55
|
-
* a terminal session failure (`session.failed`); the next turn does
|
|
56
|
-
* not retry. See `research/active/hooks.md`.
|
|
57
|
-
*/
|
|
58
|
-
export declare const SessionPreparedKey: ContextKey<boolean>;
|
|
59
50
|
export declare const SessionKey: ContextKey<Session>;
|
|
60
51
|
export declare const SandboxKey: ContextKey<SandboxAccess>;
|
|
61
52
|
export interface DurableDynamicToolMetadata {
|
package/dist/src/context/keys.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ContextKey}from"#context/key.js";const AuthKey=new ContextKey(`ash.auth`),InitiatorAuthKey=new ContextKey(`ash.initiatorAuth`),SessionIdKey=new ContextKey(`ash.sessionId`),ContinuationTokenKey=new ContextKey(`ash.continuationToken`),ChannelInstrumentationKey=new ContextKey(`ash.channelInstrumentation`),ModeKey=new ContextKey(`ash.mode`),ParentSessionKey=new ContextKey(`ash.parentSession`),CapabilitiesKey=new ContextKey(`ash.capabilities`),SessionCallbackKey=new ContextKey(`ash.sessionCallback`),
|
|
1
|
+
import{ContextKey}from"#context/key.js";const AuthKey=new ContextKey(`ash.auth`),InitiatorAuthKey=new ContextKey(`ash.initiatorAuth`),SessionIdKey=new ContextKey(`ash.sessionId`),ContinuationTokenKey=new ContextKey(`ash.continuationToken`),ChannelInstrumentationKey=new ContextKey(`ash.channelInstrumentation`),ModeKey=new ContextKey(`ash.mode`),ParentSessionKey=new ContextKey(`ash.parentSession`),CapabilitiesKey=new ContextKey(`ash.capabilities`),SessionCallbackKey=new ContextKey(`ash.sessionCallback`),SessionKey=new ContextKey(`ash.session`),SandboxKey=new ContextKey(`ash.sandbox`),SessionDynamicToolMetadataKey=new ContextKey(`ash.sessionDynamicToolMetadata`),TurnDynamicToolMetadataKey=new ContextKey(`ash.turnDynamicToolMetadata`),LiveStepToolsKey=new ContextKey(`ash.liveStepTools`),DynamicSkillManifestKey=new ContextKey(`ash.dynamicSkillManifest`),SessionDynamicInstructionsKey=new ContextKey(`ash.sessionDynamicInstructions`),TurnDynamicInstructionsKey=new ContextKey(`ash.turnDynamicInstructions`);export{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,ContinuationTokenKey,DynamicSkillManifestKey,InitiatorAuthKey,LiveStepToolsKey,ModeKey,ParentSessionKey,SandboxKey,SessionCallbackKey,SessionDynamicInstructionsKey,SessionDynamicToolMetadataKey,SessionIdKey,SessionKey,TurnDynamicInstructionsKey,TurnDynamicToolMetadataKey};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
|
|
2
|
-
import { type
|
|
2
|
+
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
3
3
|
import type { JsonObject } from "#shared/json.js";
|
|
4
4
|
/**
|
|
5
5
|
* Result returned by {@link createSessionStep}.
|
|
@@ -11,8 +11,8 @@ export interface CreateSessionStepResult {
|
|
|
11
11
|
readonly state: DurableSessionState;
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
14
|
-
* Creates the durable session and
|
|
15
|
-
*
|
|
14
|
+
* Creates the durable session and returns the initial snapshot-bearing
|
|
15
|
+
* state before the workflow enters its turn loop.
|
|
16
16
|
* `nodeId` targets a subagent node in the compiled graph; omitted for
|
|
17
17
|
* the root agent.
|
|
18
18
|
*
|
|
@@ -40,5 +40,4 @@ export declare function createSessionStep(input: {
|
|
|
40
40
|
*/
|
|
41
41
|
readonly serializedContext: Record<string, unknown>;
|
|
42
42
|
readonly sessionId: string;
|
|
43
|
-
readonly sessionWritable: WritableStream<DurableSessionSnapshot>;
|
|
44
43
|
}): Promise<CreateSessionStepResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{
|
|
1
|
+
import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{createDurableSessionState}from"#execution/durable-session-store.js";import{createSession}from"#execution/session.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentSessionId}from"#execution/ash-workflow-attributes.js";import{setAshAttributes}from"#runtime/attributes/emit.js";async function createSessionStep(e){"use step";let t=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),n=createDurableSessionState({session:createSession({compactionOverrides:{thresholdPercent:t.resolvedAgent.config.compaction?.thresholdPercent},continuationToken:e.continuationToken,outputSchema:e.outputSchema,rootSessionId:e.rootSessionId,sessionId:e.sessionId,turnAgent:t.turnAgent})}),r={nodeId:t.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},i=readParentSessionId(e.serializedContext);return i===void 0?await setAshAttributes(buildSessionAttributes({inputMessage:e.inputMessage,serializedContext:e.serializedContext})):await setAshAttributes(buildSubagentRootAttributes({identity:r,parentSessionId:i,rootSessionId:e.rootSessionId??i,serializedContext:e.serializedContext})),{state:n}}export{createSessionStep};
|
|
@@ -4,16 +4,15 @@
|
|
|
4
4
|
* Each child run starts in task mode, emits a parent `subagent.called`
|
|
5
5
|
* control-plane event, and then runs independently on its own child
|
|
6
6
|
* stream. Records each child's continuation token on the parent
|
|
7
|
-
* session and
|
|
7
|
+
* session and returns the updated snapshot-bearing state.
|
|
8
8
|
*/
|
|
9
9
|
import type { RuntimeSubagentResultActionResult } from "#runtime/actions/types.js";
|
|
10
|
-
import { type
|
|
10
|
+
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
11
11
|
export declare function dispatchRuntimeActionsStep(input: {
|
|
12
12
|
readonly callbackBaseUrl?: string;
|
|
13
13
|
readonly parentWritable: WritableStream<Uint8Array>;
|
|
14
14
|
readonly serializedContext: Record<string, unknown>;
|
|
15
15
|
readonly sessionState: DurableSessionState;
|
|
16
|
-
readonly sessionWritable: WritableStream<DurableSessionSnapshot>;
|
|
17
16
|
}): Promise<{
|
|
18
17
|
readonly results: readonly RuntimeSubagentResultActionResult[];
|
|
19
18
|
readonly sessionState: DurableSessionState;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,InitiatorAuthKey}from"#context/keys.js";import{createSubagentCalledEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{toErrorMessage}from"#shared/errors.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{readDurableSession
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,InitiatorAuthKey}from"#context/keys.js";import{createSubagentCalledEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{toErrorMessage}from"#shared/errors.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch,recordPendingSubagentChildToken}from"#harness/runtime-actions.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/remote-agent-dispatch.js";import{buildSubagentRunInput}from"#execution/subagent-tool.js";import{createWorkflowRuntime,workflowEntryReference}from"#execution/workflow-runtime.js";const log=createLogger(`execution.dispatch-runtime-actions`);async function dispatchRuntimeActionsStep(e){"use step";let s=await readDurableSession(e.sessionState),u=getPendingRuntimeActionBatch(s.state);if(u===void 0||u.actions.length===0)return{results:[],sessionState:e.sessionState};let d=await deserializeContext(e.serializedContext),f=d.require(BundleKey),p=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.resolvedAgent.config.compaction?.thresholdPercent},durable:s,turnAgent:f.turnAgent}),m=d.require(ChannelKey),h=d.get(AuthKey)??null,g=d.get(CapabilitiesKey),_=d.get(InitiatorAuthKey)??null,v=e.parentWritable.getWriter(),y=buildAdapterContext(m,d),b=p,x=[];try{for(let r of u.actions){let i,a,s,c;switch(r.kind){case`subagent-call`:{let e=createWorkflowRuntime({compiledArtifactsSource:f.compiledArtifactsSource,nodeId:r.nodeId}),{childContinuationToken:t,runInput:n}=buildSubagentRunInput({action:r,auth:h,batchEvent:u.event,capabilities:g,initiatorAuth:_,session:p}),o=await e.run(n);b=recordPendingSubagentChildToken({callId:r.callId,childContinuationToken:t,session:b}),i=o.sessionId,a=r.name,c=r.subagentName;break}case`remote-agent-call`:{let n;try{n=resolveRemoteAgentForAction({nodeId:r.nodeId,remoteAgentName:r.remoteAgentName,registry:f.subagentRegistry.subagentsByNodeId}),i=await startRemoteAgentSession({action:r,callbackBaseUrl:e.callbackBaseUrl,remote:n,session:p})}catch(e){logError(log,`remote agent start failed`,e,{remoteAgentName:r.remoteAgentName,nodeId:r.nodeId,callId:r.callId}),x.push(createRemoteAgentStartFailureResult({action:r,error:e}));continue}a=r.name,s={url:n.url},c=r.remoteAgentName;break}default:throw Error(`Unsupported runtime action kind "${r.kind}" in workflow runtime.`)}let l=await callAdapterEventHandler(m,createSubagentCalledEvent({callId:r.callId,childSessionId:i,name:a,remote:s,sequence:u.event.sequence,sessionId:p.sessionId,toolName:c,turnId:u.event.turnId,workflowId:workflowEntryReference.workflowId}),y);await v.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(l)))}}finally{v.releaseLock()}return{results:x,sessionState:b===p?e.sessionState:createDurableSessionState({session:b})}}function createRemoteAgentStartFailureResult(e){return{callId:e.action.callId,isError:!0,kind:`subagent-result`,output:{code:`REMOTE_AGENT_START_FAILED`,message:toErrorMessage(e.error)},subagentName:e.action.remoteAgentName}}export{dispatchRuntimeActionsStep};
|