typeclaw 0.42.0 → 0.43.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/auth.schema.json +16 -0
- package/package.json +3 -3
- package/secrets.schema.json +16 -0
- package/src/agent/adaptive-thinking-compat.ts +79 -0
- package/src/agent/index.ts +79 -101
- package/src/agent/live-subagents.ts +4 -4
- package/src/agent/plugin-tools.ts +85 -132
- package/src/agent/provider-error.ts +37 -0
- package/src/agent/reload-tool.ts +1 -1
- package/src/agent/session-origin.ts +6 -3
- package/src/agent/subagents.ts +2 -2
- package/src/agent/system-prompt.ts +24 -8
- package/src/agent/tool-result-budget.ts +1 -1
- package/src/agent/tools/channel-react.ts +5 -4
- package/src/agent/tools/spawn-subagent.ts +80 -24
- package/src/agent/tools/stream-snapshot.ts +8 -3
- package/src/bundled-plugins/agent-browser/index.ts +18 -8
- package/src/bundled-plugins/memory/README.md +4 -1
- package/src/bundled-plugins/memory/belief-sentence.ts +50 -0
- package/src/bundled-plugins/memory/dreaming.ts +13 -6
- package/src/bundled-plugins/memory/load-memory.ts +22 -2
- package/src/bundled-plugins/memory/memory-logger.ts +1 -1
- package/src/bundled-plugins/planner/planner.ts +1 -1
- package/src/bundled-plugins/researcher/researcher.ts +2 -2
- package/src/bundled-plugins/reviewer/reviewer.ts +1 -1
- package/src/capabilities/control-plane.ts +24 -0
- package/src/capabilities/index.ts +2 -0
- package/src/capabilities/runtime.ts +30 -0
- package/src/channels/adapters/discord-bot-thread-room.ts +73 -0
- package/src/channels/adapters/discord-bot.ts +9 -1
- package/src/channels/adapters/slack-bot-classify.ts +1 -0
- package/src/channels/adapters/slack-classify.ts +1 -0
- package/src/channels/engagement.ts +33 -0
- package/src/channels/manager.ts +41 -47
- package/src/channels/router.ts +150 -21
- package/src/channels/types.ts +10 -0
- package/src/cli/channel.ts +49 -12
- package/src/cli/command-meta.ts +2 -0
- package/src/cli/hostd.ts +4 -3
- package/src/cli/index.ts +1 -0
- package/src/cli/logs.ts +2 -2
- package/src/cli/mcp.ts +233 -0
- package/src/cli/restart.ts +5 -3
- package/src/cli/shell.ts +2 -2
- package/src/cli/start.ts +2 -2
- package/src/cli/status.ts +2 -2
- package/src/cli/stop.ts +2 -2
- package/src/compose/restart.ts +4 -3
- package/src/compose/start.ts +2 -2
- package/src/compose/stop.ts +2 -2
- package/src/config/config.ts +10 -1
- package/src/config/providers.ts +61 -9
- package/src/container/controller.ts +104 -0
- package/src/container/index.ts +9 -0
- package/src/hostd/daemon.ts +28 -9
- package/src/hostd/protocol.ts +12 -9
- package/src/init/index.ts +1 -1
- package/src/init/instagram-auth.ts +189 -34
- package/src/inspect/logs-item.ts +2 -2
- package/src/mcp/client.ts +16 -6
- package/src/mcp/index.ts +12 -0
- package/src/mcp/manager.ts +9 -4
- package/src/mcp/oauth.ts +212 -0
- package/src/run/index.ts +36 -11
- package/src/run/{codex-fetch-observer.ts → llm-fetch-observer.ts} +182 -82
- package/src/sandbox/availability.ts +2 -2
- package/src/sandbox/build.ts +1 -1
- package/src/sandbox/hidden-paths.ts +59 -0
- package/src/sandbox/index.ts +1 -1
- package/src/sandbox/policy.ts +2 -2
- package/src/secrets/discord-store.ts +4 -13
- package/src/secrets/index.ts +1 -1
- package/src/secrets/instagram-store.ts +4 -13
- package/src/secrets/kakao-store.ts +4 -13
- package/src/secrets/line-store.ts +4 -13
- package/src/secrets/schema.ts +13 -0
- package/src/secrets/secrets-provider.ts +86 -0
- package/src/secrets/slack-store.ts +4 -13
- package/src/secrets/storage.ts +108 -1
- package/src/secrets/webex-store.ts +4 -13
- package/src/server/index.ts +2 -2
- package/src/skills/typeclaw-channel-github/SKILL.md +2 -2
- package/src/skills/typeclaw-channel-instagram/SKILL.md +1 -1
- package/src/skills/typeclaw-config/SKILL.md +5 -3
- package/src/skills/typeclaw-plugins/SKILL.md +1 -1
- package/src/skills/typeclaw-troubleshooting/SKILL.md +1 -1
- package/src/stream/broker.ts +4 -3
- package/src/stream/types.ts +1 -0
- package/typeclaw.schema.json +14 -0
|
@@ -78,14 +78,16 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
|
|
|
78
78
|
description: '3-5 word label for this spawn, used for logs and the status_summary. Optional.',
|
|
79
79
|
}),
|
|
80
80
|
),
|
|
81
|
-
|
|
81
|
+
run_in_foreground: Type.Optional(
|
|
82
82
|
Type.Boolean({
|
|
83
83
|
description:
|
|
84
|
-
'
|
|
85
|
-
'When
|
|
86
|
-
'
|
|
87
|
-
'
|
|
88
|
-
'
|
|
84
|
+
'Request a FOREGROUND (synchronous) spawn: the tool blocks until the subagent finishes and returns its final message inline. ' +
|
|
85
|
+
'When omitted (the default) from a top-level session, the spawn runs in the BACKGROUND — it returns a task_id immediately and a system-reminder arrives when it completes; do NOT poll subagent_output. ' +
|
|
86
|
+
'The runtime may override your request and always states which mode it used and why in the tool result: ' +
|
|
87
|
+
'a deep-profile subagent spawned from a top-level session is forced to the background (a foreground run would freeze this session while it works), ' +
|
|
88
|
+
'and a background spawn requested from a subagent session that cannot drain child results is degraded to foreground so the result still reaches you. ' +
|
|
89
|
+
'From a subagent session the default is foreground — which is what you need to fold a delegated result into your own output; ' +
|
|
90
|
+
'for PARALLEL fan-out, emit several foreground spawns in a SINGLE turn and their results return together.',
|
|
89
91
|
}),
|
|
90
92
|
),
|
|
91
93
|
profile: Type.Optional(
|
|
@@ -115,17 +117,19 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
|
|
|
115
117
|
`subagent.spawn denied: maximum delegation depth (${MAX_SUBAGENT_DEPTH}) reached; a subagent at this depth cannot spawn further subagents`,
|
|
116
118
|
)
|
|
117
119
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
120
|
+
const subagentName = params.subagent_type
|
|
121
|
+
const { background, overrideNote } = resolveSpawnMode({
|
|
122
|
+
foreground: params.run_in_foreground,
|
|
123
|
+
fromSubagent: origin?.kind === 'subagent',
|
|
124
|
+
// Deep-profile spawns run for minutes; forcing them background from a
|
|
125
|
+
// top-level session keeps a foreground run from freezing the message
|
|
126
|
+
// loop. Per-spawn override wins over the declared profile.
|
|
127
|
+
isDeepProfile: (params.profile ?? subagent.profile) === 'deep',
|
|
128
|
+
canBackgroundFromSubagent: allowBackgroundFromSubagent === true,
|
|
129
|
+
subagentName,
|
|
130
|
+
})
|
|
125
131
|
|
|
126
132
|
const taskId = generateTaskId()
|
|
127
|
-
const subagentName = params.subagent_type
|
|
128
|
-
const background = params.run_in_background === true
|
|
129
133
|
const payload: Record<string, unknown> = { requestId: taskId, prompt: params.prompt }
|
|
130
134
|
if (params.description !== undefined) payload.description = params.description
|
|
131
135
|
if (params.profile !== undefined) payload.profile = params.profile
|
|
@@ -200,11 +204,12 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
|
|
|
200
204
|
taskId,
|
|
201
205
|
sessionId: resolvedHandle.sessionId,
|
|
202
206
|
}
|
|
207
|
+
const baseText = `Spawned ${subagentName} in background. task_id=${taskId}. You will receive a system-reminder when it completes. Use subagent_output to check progress or fetch results.`
|
|
203
208
|
return {
|
|
204
209
|
content: [
|
|
205
210
|
{
|
|
206
211
|
type: 'text' as const,
|
|
207
|
-
text:
|
|
212
|
+
text: overrideNote !== undefined ? `${overrideNote}\n\n${baseText}` : baseText,
|
|
208
213
|
},
|
|
209
214
|
],
|
|
210
215
|
details,
|
|
@@ -223,11 +228,12 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
|
|
|
223
228
|
result.finalMessage !== undefined
|
|
224
229
|
? ` It produced output before failing; recover it below instead of redoing the work:\n\n${result.finalMessage}`
|
|
225
230
|
: ''
|
|
231
|
+
const failureText = `${subagentName} failed after ${durationMs}ms: ${result.error}.${recovered}`
|
|
226
232
|
return {
|
|
227
233
|
content: [
|
|
228
234
|
{
|
|
229
235
|
type: 'text' as const,
|
|
230
|
-
text: `${
|
|
236
|
+
text: overrideNote !== undefined ? `${overrideNote}\n\n${failureText}` : failureText,
|
|
231
237
|
},
|
|
232
238
|
],
|
|
233
239
|
details,
|
|
@@ -242,14 +248,15 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
|
|
|
242
248
|
durationMs,
|
|
243
249
|
...(result.finalMessage !== undefined ? { finalMessage: result.finalMessage } : {}),
|
|
244
250
|
}
|
|
251
|
+
const syncText =
|
|
252
|
+
result.finalMessage !== undefined
|
|
253
|
+
? result.finalMessage
|
|
254
|
+
: `${subagentName} completed in ${durationMs}ms with no final message.`
|
|
245
255
|
return {
|
|
246
256
|
content: [
|
|
247
257
|
{
|
|
248
258
|
type: 'text' as const,
|
|
249
|
-
text:
|
|
250
|
-
result.finalMessage !== undefined
|
|
251
|
-
? result.finalMessage
|
|
252
|
-
: `${subagentName} completed in ${durationMs}ms with no final message.`,
|
|
259
|
+
text: overrideNote !== undefined ? `${overrideNote}\n\n${syncText}` : syncText,
|
|
253
260
|
},
|
|
254
261
|
],
|
|
255
262
|
details,
|
|
@@ -265,9 +272,9 @@ export function spawnSubagentDescription(registry: SubagentRegistry): string {
|
|
|
265
272
|
`Spawn a subagent to do focused work on your behalf. Use this when a task is heavy enough to deserve a fresh context window (research fan-out) ` +
|
|
266
273
|
`or long-running enough that you want to keep the conversation moving while it runs (delegate-and-converse). ` +
|
|
267
274
|
`Available subagents: ${available}. ` +
|
|
268
|
-
`
|
|
269
|
-
`
|
|
270
|
-
`
|
|
275
|
+
`The default mode depends on the caller's origin: a top-level session defaults to background (the tool returns a task_id immediately and a system-reminder arrives when the subagent completes — do NOT poll subagent_output), while a subagent session defaults to foreground so the result folds into your own output. ` +
|
|
276
|
+
`Pass run_in_foreground=true to force a blocking inline result, or run_in_foreground=false to request background. ` +
|
|
277
|
+
`The runtime may override the mode and states which it used and why in the tool result (a deep-profile subagent is forced to the background from a top-level session; a background request from a subagent that cannot drain child results degrades to foreground). ` +
|
|
271
278
|
`The delegation chain is depth-limited: a subagent you spawn may itself delegate once more, but no deeper — ` +
|
|
272
279
|
`keep your delegation tree shallow.`
|
|
273
280
|
)
|
|
@@ -360,3 +367,52 @@ function errorResult(message: string): ToolReturn {
|
|
|
360
367
|
details,
|
|
361
368
|
}
|
|
362
369
|
}
|
|
370
|
+
|
|
371
|
+
export type SpawnModeResolution = {
|
|
372
|
+
background: boolean
|
|
373
|
+
overrideNote: string | undefined
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// Resolve foreground vs background for a spawn, with the runtime free to
|
|
377
|
+
// override the caller's request and report why. Two axes decide it: whether the
|
|
378
|
+
// caller is a top-level session (its turn services the live message loop) or a
|
|
379
|
+
// subagent (its turn does not), and whether the child runs on the deep profile.
|
|
380
|
+
// `foreground` is the tri-state tool param: undefined means the caller did not
|
|
381
|
+
// choose, so the origin default applies.
|
|
382
|
+
//
|
|
383
|
+
// - Top-level default is background: a long child must not block the loop.
|
|
384
|
+
// Deep-profile children are forced background even when foreground is asked.
|
|
385
|
+
// - Subagent default is foreground: the sync result folds into the caller's own
|
|
386
|
+
// output (e.g. planner -> reviewer). A subagent can still opt into background
|
|
387
|
+
// with foreground=false, but only when the runtime can drain child
|
|
388
|
+
// completions; otherwise that request degrades to foreground so the result is
|
|
389
|
+
// not lost.
|
|
390
|
+
export function resolveSpawnMode(input: {
|
|
391
|
+
foreground: boolean | undefined
|
|
392
|
+
fromSubagent: boolean
|
|
393
|
+
isDeepProfile: boolean
|
|
394
|
+
canBackgroundFromSubagent: boolean
|
|
395
|
+
subagentName: string
|
|
396
|
+
}): SpawnModeResolution {
|
|
397
|
+
const { foreground, fromSubagent, isDeepProfile, canBackgroundFromSubagent, subagentName } = input
|
|
398
|
+
|
|
399
|
+
if (fromSubagent) {
|
|
400
|
+
const wantsBackground = foreground === false
|
|
401
|
+
if (wantsBackground && !canBackgroundFromSubagent) {
|
|
402
|
+
return {
|
|
403
|
+
background: false,
|
|
404
|
+
overrideNote: `\`${subagentName}\` was spawned in the FOREGROUND: a subagent session cannot drain background children after its turn ends, so a foreground run is the only way its result reaches you.`,
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return { background: wantsBackground, overrideNote: undefined }
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
if (isDeepProfile && foreground === true) {
|
|
411
|
+
return {
|
|
412
|
+
background: true,
|
|
413
|
+
overrideNote: `\`${subagentName}\` was spawned in the BACKGROUND despite the foreground request: it runs on the deep profile (minutes of work), and a foreground run would freeze this session until it finished. A completion reminder will arrive when it is done.`,
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
return { background: foreground !== true, overrideNote: undefined }
|
|
418
|
+
}
|
|
@@ -13,9 +13,13 @@ type TargetKind = (typeof TARGET_KINDS)[number]
|
|
|
13
13
|
|
|
14
14
|
export type CreateStreamSnapshotToolOptions = {
|
|
15
15
|
stream: Stream
|
|
16
|
+
// Clock source for the `since_ms_ago` cutoff. Defaults to the real clock;
|
|
17
|
+
// injectable so tests can pin `now` and assert the time filter without
|
|
18
|
+
// depending on wall-clock timing between publish and execute.
|
|
19
|
+
now?: () => number
|
|
16
20
|
}
|
|
17
21
|
|
|
18
|
-
export function createStreamSnapshotTool({ stream }: CreateStreamSnapshotToolOptions) {
|
|
22
|
+
export function createStreamSnapshotTool({ stream, now = Date.now }: CreateStreamSnapshotToolOptions) {
|
|
19
23
|
return defineTool({
|
|
20
24
|
name: 'stream_snapshot',
|
|
21
25
|
label: 'Stream Snapshot',
|
|
@@ -54,7 +58,7 @@ export function createStreamSnapshotTool({ stream }: CreateStreamSnapshotToolOpt
|
|
|
54
58
|
|
|
55
59
|
async execute(_toolCallId, params) {
|
|
56
60
|
const limit = clampLimit(params.limit)
|
|
57
|
-
const filter = buildFilter(params.target_kind, params.target_id, params.since_ms_ago, limit)
|
|
61
|
+
const filter = buildFilter(params.target_kind, params.target_id, params.since_ms_ago, limit, now)
|
|
58
62
|
const events = stream.scan(filter)
|
|
59
63
|
return formatResult(events, params)
|
|
60
64
|
},
|
|
@@ -71,10 +75,11 @@ function buildFilter(
|
|
|
71
75
|
id: string | undefined,
|
|
72
76
|
sinceMsAgo: number | undefined,
|
|
73
77
|
limit: number,
|
|
78
|
+
now: () => number,
|
|
74
79
|
): ScanFilter {
|
|
75
80
|
const filter: ScanFilter = { limit }
|
|
76
81
|
if (kind !== undefined) filter.target = buildTargetFilter(kind, id)
|
|
77
|
-
if (sinceMsAgo !== undefined) filter.sinceTs =
|
|
82
|
+
if (sinceMsAgo !== undefined) filter.sinceTs = now() - sinceMsAgo
|
|
78
83
|
return filter
|
|
79
84
|
}
|
|
80
85
|
|
|
@@ -9,8 +9,17 @@ type SafeResult = InstallShimResult | { kind: 'error'; binPath: string; error: u
|
|
|
9
9
|
|
|
10
10
|
// Documented in skills/agent-browser/SKILL.md so the agent can discover which
|
|
11
11
|
// host port the reserved dashboard forward actually bound. Moving or renaming
|
|
12
|
-
// this path requires updating the skill in lockstep.
|
|
13
|
-
|
|
12
|
+
// this path requires updating the skill in lockstep. The env override is an
|
|
13
|
+
// internal escape hatch for the parallel test harness (many worker processes on
|
|
14
|
+
// one host must not clobber a single shared /tmp path); production uses the
|
|
15
|
+
// documented default and the skill contract is unchanged.
|
|
16
|
+
const DEFAULT_PROXY_PORT_HINT_PATH = '/tmp/typeclaw-agent-browser-proxy-port'
|
|
17
|
+
const PROXY_PORT_HINT_PATH_ENV = 'TYPECLAW_AGENT_BROWSER_PROXY_PORT_HINT_PATH'
|
|
18
|
+
|
|
19
|
+
function proxyPortHintPath(): string {
|
|
20
|
+
return process.env[PROXY_PORT_HINT_PATH_ENV] || DEFAULT_PROXY_PORT_HINT_PATH
|
|
21
|
+
}
|
|
22
|
+
|
|
14
23
|
const DASHBOARD_TARGET_PORT = 4848
|
|
15
24
|
const DASHBOARD_HOST_CANDIDATES = [4848, 4849, 4850, 4851, 4852, 4853, 4854, 4855, 4856, 4857] as const
|
|
16
25
|
|
|
@@ -37,7 +46,7 @@ export function __resetForwardRequestForTesting(): void {
|
|
|
37
46
|
|
|
38
47
|
function requestDashboardForward(logger: { info: (msg: string) => void; warn: (msg: string) => void }): void {
|
|
39
48
|
if (!defaultBrokerEnabled()) {
|
|
40
|
-
recordProxyPort('TypeClaw dashboard forwarding unavailable: hostd broker is disabled.', logger)
|
|
49
|
+
void recordProxyPort('TypeClaw dashboard forwarding unavailable: hostd broker is disabled.', logger)
|
|
41
50
|
return
|
|
42
51
|
}
|
|
43
52
|
|
|
@@ -45,11 +54,11 @@ function requestDashboardForward(logger: { info: (msg: string) => void; warn: (m
|
|
|
45
54
|
unsubscribeForwardResult = subscribeForwardResult((event) => {
|
|
46
55
|
if (event.port !== DASHBOARD_TARGET_PORT) return
|
|
47
56
|
if (event.ok) {
|
|
48
|
-
recordProxyPort(String(event.hostPort), logger)
|
|
57
|
+
void recordProxyPort(String(event.hostPort), logger)
|
|
49
58
|
logger.info(`agent-browser dashboard forward reserved on host:${event.hostPort}`)
|
|
50
59
|
return
|
|
51
60
|
}
|
|
52
|
-
recordProxyPort(`TypeClaw dashboard forwarding unavailable: ${event.reason}`, logger)
|
|
61
|
+
void recordProxyPort(`TypeClaw dashboard forwarding unavailable: ${event.reason}`, logger)
|
|
53
62
|
logger.warn(`agent-browser dashboard forward failed: ${event.reason}`)
|
|
54
63
|
})
|
|
55
64
|
}
|
|
@@ -66,13 +75,14 @@ function defaultBrokerEnabled(): boolean {
|
|
|
66
75
|
return token !== undefined && token.length > 0
|
|
67
76
|
}
|
|
68
77
|
|
|
69
|
-
function recordProxyPort(contents: string, logger: { warn: (msg: string) => void }): void {
|
|
78
|
+
async function recordProxyPort(contents: string, logger: { warn: (msg: string) => void }): Promise<void> {
|
|
79
|
+
const path = proxyPortHintPath()
|
|
70
80
|
try {
|
|
71
|
-
Bun.write(
|
|
81
|
+
await Bun.write(path, contents)
|
|
72
82
|
} catch (error) {
|
|
73
83
|
// Hint is informational (lets a future `typeclaw status` or a human shell
|
|
74
84
|
// session report which port to open). Failure is non-fatal.
|
|
75
|
-
logger.warn(`failed to write ${
|
|
85
|
+
logger.warn(`failed to write ${path}: ${String(error)}`)
|
|
76
86
|
}
|
|
77
87
|
}
|
|
78
88
|
|
|
@@ -47,7 +47,9 @@ Memory is injected per turn into the user prompt; the system prompt never contai
|
|
|
47
47
|
|
|
48
48
|
**Cross-turn dedup (direct mode, non-channel).** Re-sending every shard body verbatim on every turn made a long conversation pay the same memory block dozens of times. The plugin keeps a per-session `slug → body-hash` record (`turn-dedup.ts`, `partitionDirectShards`) and, after a shard's full body has been injected once this session, replaces it on later turns with a one-line `slug:` reference plus a `memory_search({ topic: "<slug>" })` recovery hint. A shard whose body **changed** (a dreaming pass rewrote it) re-injects in full so the agent never reasons over a stale body. The "nothing the agent always had vanishes on an off-topic turn" guarantee is preserved by **availability, not literal presence**: every topic is still named (heading + slug) every turn, and the full body is one `memory_search` away. The per-session record is cleared on `session.end` (before the subagent-origin early-return, so subagent sessions don't leak it), so a resurrected session re-injects bodies in full rather than dangling a reference to text the rebuilt context no longer holds.
|
|
49
49
|
|
|
50
|
-
For **channel** origins, the per-turn render injects topic **headings only** — the excerpt body is stripped and the agent fetches it on demand via `memory_search`. A channel **direct-mode** turn is force-indexed to a headings/slugs section over **every** shard (not run through `hybridSearch`), so a full body can never reach a channel turn AND no heading is silently dropped by relevance-filtering or a stale vector index. Only channel turns that are genuinely **over budget** fall to `hybridSearch` top-K, where headings-only injection is the established channel policy regardless. This mirrors the direct-path policy that channel sessions never carry bodies: a topic heading is a self-contained belief sentence (the dreaming subagent writes exactly one), so the heading alone lets the model decide whether the topic is worth opening,
|
|
50
|
+
For **channel** origins, the per-turn render injects topic **headings only** — the excerpt body is stripped and the agent fetches it on demand via `memory_search`. A channel **direct-mode** turn is force-indexed to a headings/slugs section over **every** shard (not run through `hybridSearch`), so a full body can never reach a channel turn AND no heading is silently dropped by relevance-filtering or a stale vector index. Only channel turns that are genuinely **over budget** fall to `hybridSearch` top-K, where headings-only injection is the established channel policy regardless. This mirrors the direct-path policy that channel sessions never carry bodies: a topic heading is a self-contained belief sentence (the dreaming subagent writes exactly one — dreaming rule 6 requires the `heading` frontmatter to BE that belief sentence, not a noun-phrase title), so the heading alone lets the model decide whether the topic is worth opening — and, unlike a bare title, carries the fact itself so a casual turn that never calls `memory_search` still sees current truth instead of falling back to a stale model prior. The ~10-shard excerpt block — which dominated the per-turn injection and was usually abandoned unread — no longer rides in the (uncacheable) user turn on every message. Non-channel origins (TUI/direct) keep the full excerpt on first injection, where the extra retrieval round-trip isn't worth it.
|
|
51
|
+
|
|
52
|
+
**Legacy title-like headings.** A pre-contract shard whose `heading` is a noun-phrase title (detected as a clean kebab echo of its slug via `slugIsHeadingEcho`) would leave a channel turn with a fact-free label. `channelTopicEntry` (`load-memory.ts`) recovers the shard's first belief sentence from the body (`firstBeliefSentence`, `belief-sentence.ts`) and surfaces THAT instead — bounded to one sentence, never the full body, so the memory-bleed posture is unchanged. Both channel paths (direct-mode force-index and over-budget `hybridSearch` top-K) apply the fallback. Detection and extraction are script-agnostic (an all-CJK/Korean heading never reads as a slug echo, so a Korean belief-sentence heading is never mistaken for a title). This is the render-time bridge for shards written before the rule-6 heading contract; new/re-dreamed shards get belief-sentence headings natively.
|
|
51
53
|
|
|
52
54
|
Each stripped topic is injected with its `slug:` line so the agent can re-fetch the exact shard with `memory_search({ topic: "<slug>" })` — a direct slug lookup, not a second fuzzy search over the heading text the retrieval layer already matched. Undreamed `source: "stream"` items have no topic shard yet (no slug to look up), so they instead carry a `memory_search({ query: ... })` recovery hint; the channel directive names both paths so every stripped entry — topic or stream — has an explicit way back to its full text.
|
|
53
55
|
|
|
@@ -93,6 +95,7 @@ The subagent uses these signals to:
|
|
|
93
95
|
1. **Promote strong topics.** `days = 1` → tentative ("the user mentioned"). `days >= 3` → confident ("the user consistently"). `days >= 7` → declarative ("the user always"). Promotion is gated on distinct days, not raw citation count.
|
|
94
96
|
2. **Merge near-duplicates.** Topics that overlap get folded into one. The merged topic's citation set is the union.
|
|
95
97
|
3. **Demote decayed topics.** A weak/decayed topic stays as its own shard but the body should be trimmed to a single line. When index-mode injection is in effect, demoted shards' bodies don't enter the user turn at all — the index plus `memory_search` retrieval cover them on demand.
|
|
98
|
+
4. **Reinforce reaffirmed topics.** When a new fragment reaffirms, repeats, or user-corrects toward the current truth an existing shard already holds, the subagent adds that fragment id to the shard's `fragments:` list — a **distinct path from contradiction** (which supersedes) and from drop (which discards). Because the runtime recomputes `cites`/`days`/`lastReinforced` from the citation list, adding a citation IS the reinforcement mechanism; the subagent never edits the numbers. Reinforcement never moves an id into `superseded:` (that is contradiction-only). The dreaming prompt caps this at one pure-reinforcement citation per shard per day so a same-day burst can't inflate `days`, the promotion signal. This is what makes a fact the user repeatedly corrects get _stronger_ over time instead of being discarded as "already known" — and a correction that reveals a recurring wrong belief also sharpens the belief sentence with an explicit negative guard ("X is not Y anymore; X is Z"), which post-headings-fix is exactly what a channel turn sees first. The complementary capture half lives in the memory-logger prompt, which records a user correction as a distinct evidence-anchored fragment (semantically, in any language) even when memory may already know the affirmative fact.
|
|
96
99
|
|
|
97
100
|
There is no `## Historical observations` bucket. Demoted topics live as their own shards; injection-time filtering (the index/direct split) handles the prompt-budget pressure.
|
|
98
101
|
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { stripCitationLines } from './citations'
|
|
2
|
+
import { slugIsHeadingEcho } from './slug'
|
|
3
|
+
|
|
4
|
+
// Channel injection shows the agent only the heading, assuming the heading IS the
|
|
5
|
+
// shard's self-contained belief sentence. Legacy/dreaming shards put a noun-phrase
|
|
6
|
+
// TITLE there and the belief sentence in the body, so channel turns see a bare
|
|
7
|
+
// title carrying no fact. These helpers recover the belief sentence so a channel
|
|
8
|
+
// render can surface it — bounded to ONE sentence, never the full body, so the
|
|
9
|
+
// memory-bleed posture is unchanged. Script-agnostic by design (agents run in
|
|
10
|
+
// Korean/CJK/Arabic): no ASCII `\b`, no English stopword/verb heuristics.
|
|
11
|
+
|
|
12
|
+
const REFERENCES_HEADING = /^[\s-]*references\s*:\s*$/i
|
|
13
|
+
|
|
14
|
+
// Sentence terminators across the scripts agents run in: Latin `.!?`, CJK/fullwidth
|
|
15
|
+
// `。!?`, Arabic question mark `؟`, and Devanagari danda `।`. `\.` is only treated
|
|
16
|
+
// as a terminator when followed by whitespace or end-of-string, so a decimal like
|
|
17
|
+
// `3.5` or `v1.2` inside the belief does not cut the sentence short.
|
|
18
|
+
const SENTENCE_END = /[。!?؟।!?]|\.(?=\s|$)/u
|
|
19
|
+
|
|
20
|
+
// The first sentence of `line`: text up to and including the first terminator. A
|
|
21
|
+
// line with no terminator (a title/label) is itself one sentence and returned whole.
|
|
22
|
+
function firstSentenceOf(line: string): string {
|
|
23
|
+
const match = SENTENCE_END.exec(line)
|
|
24
|
+
if (match === null) return line
|
|
25
|
+
return line.slice(0, match.index + match[0].length).trim()
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function firstBeliefSentence(body: string): string | undefined {
|
|
29
|
+
const prose = stripCitationLines(body)
|
|
30
|
+
for (const raw of prose.split('\n')) {
|
|
31
|
+
const line = raw.trim()
|
|
32
|
+
if (line === '') continue
|
|
33
|
+
if (REFERENCES_HEADING.test(line)) continue
|
|
34
|
+
const unwrapped = line.replace(/^#{1,6}\s+/, '').trim()
|
|
35
|
+
if (unwrapped !== '') return firstSentenceOf(unwrapped)
|
|
36
|
+
}
|
|
37
|
+
return undefined
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// A heading is "title-like" (a noun-phrase label) rather than a self-contained
|
|
41
|
+
// belief sentence. The cheap, language-agnostic signal: a heading that is a clean
|
|
42
|
+
// kebab echo of its own slug ("T1 Competition Status 2026" -> `t1-competition-
|
|
43
|
+
// status-2026`) is a title, because a real belief sentence (with a predicate and
|
|
44
|
+
// scope) does not survive slugification as a clean echo — it is too long and
|
|
45
|
+
// carries punctuation/particles that `headingToSlug` collapses. `slugIsHeadingEcho`
|
|
46
|
+
// already returns false for all-CJK/emoji headings (normalization discarded
|
|
47
|
+
// content), so a Korean belief sentence is never misread as a title by this path.
|
|
48
|
+
export function isTitleLikeHeading(heading: string, slug: string): boolean {
|
|
49
|
+
return slugIsHeadingEcho(heading, slug)
|
|
50
|
+
}
|
|
@@ -10,6 +10,7 @@ import { type AgentGit, resolveAgentGit } from '@/git/resolve-agent-git'
|
|
|
10
10
|
import { defineTool, lsTool, readTool, type Subagent, writeTool } from '@/plugin'
|
|
11
11
|
import { formatLocalDate, formatLocalDateTime } from '@/shared'
|
|
12
12
|
|
|
13
|
+
import { firstBeliefSentence } from './belief-sentence'
|
|
13
14
|
import { checkCitationSupersetAcrossShards, summarizeMissingCitations } from './citation-superset'
|
|
14
15
|
import { parseCitations } from './citations'
|
|
15
16
|
import { deleteTopicShardTool } from './delete-tool'
|
|
@@ -717,8 +718,14 @@ function defaultShardFrontmatter(heading: string, tags?: string[]): ShardFrontma
|
|
|
717
718
|
return { heading, cites: 0, days: 0, lastReinforced: formatLocalDate(), ...(tags !== undefined ? { tags } : {}) }
|
|
718
719
|
}
|
|
719
720
|
|
|
721
|
+
// When the subagent omits a heading, synthesize one from the body: a `## heading`
|
|
722
|
+
// line if present (older shard shape), else the first belief sentence — which the
|
|
723
|
+
// channel-injection contract wants the heading to be. An existing subagent-authored
|
|
724
|
+
// heading is left untouched; runtime owns only cites/days/lastReinforced, not the
|
|
725
|
+
// heading text. Legacy title-like headings are recovered at render time instead
|
|
726
|
+
// (channelTopicEntry), never by silently rewriting subagent-authored content.
|
|
720
727
|
function synthesizeHeadingFromBody(body: string): string | undefined {
|
|
721
|
-
return body.match(/^##\s+(.+)$/m)?.[1]?.trim()
|
|
728
|
+
return body.match(/^##\s+(.+)$/m)?.[1]?.trim() ?? firstBeliefSentence(body)
|
|
722
729
|
}
|
|
723
730
|
|
|
724
731
|
function isEnoent(err: unknown): boolean {
|
|
@@ -1008,9 +1015,9 @@ A fragment with no useful content (a watermark-only marker, a near-duplicate, a
|
|
|
1008
1015
|
|
|
1009
1016
|
**4. Inherit the memory-logger's standards.** The memory-logger already filtered fragments using strict certainty rules (explicit / deductive / inductive). Your job is consolidation, not loosening the bar. If two fragments contradict, prefer the more recent. If a fragment is ambiguous in isolation but clarified by a later fragment, merge them under one topic. Never promote a single fragment from one day into a stable claim unless its certainty was already \`explicit\` or \`deductive\`.
|
|
1010
1017
|
|
|
1011
|
-
**5. Rebalance every run. Preserve every fact and every cited fragment id.** The shard set is a saturated surface (a fixed prompt-budget), not an append-only log — every run is consolidation, not just the runs that get new fragments. You may merge near-duplicate topics into one, split overloaded topics, rename unclear slugs/headings, and rewrite verbose conclusion paragraphs more tightly. What you must NOT do: drop a fragment id. The merged topic's \`fragments:\` list is the **union** of its source topics' fragment ids. The daily-stream GC depends on shard citations to keep evidence alive; an omitted id means the underlying fragment is permanently deleted on the next compaction. If two topics genuinely cover different facts, leave them separate — premature merging loses signal. If a new fragment contradicts an existing entry, replace the entry's conclusion paragraph to state the new current truth, and **move the old, now-overturned fragment id from \`fragments:\` into a \`superseded:\` list** in the same shard (the new fragment id goes under \`fragments:\`). Both lists keep the ids cited, so no evidence is lost — but \`superseded:\` marks the old evidence as history, not current truth, so retrieval no longer surfaces it as a hook for the new belief. Citation-superset invariant: every previously-cited fragment id must still appear cited in at least one shard after your run, in EITHER \`fragments:\` or \`superseded:\`. If you violate this, the runtime reverts your whole run.
|
|
1018
|
+
**5. Rebalance every run. Preserve every fact and every cited fragment id.** The shard set is a saturated surface (a fixed prompt-budget), not an append-only log — every run is consolidation, not just the runs that get new fragments. You may merge near-duplicate topics into one, split overloaded topics, rename unclear slugs/headings, and rewrite verbose conclusion paragraphs more tightly. What you must NOT do: drop a fragment id. The merged topic's \`fragments:\` list is the **union** of its source topics' fragment ids. The daily-stream GC depends on shard citations to keep evidence alive; an omitted id means the underlying fragment is permanently deleted on the next compaction. If two topics genuinely cover different facts, leave them separate — premature merging loses signal. If a new fragment contradicts an existing entry, replace the entry's conclusion paragraph to state the new current truth, and **move the old, now-overturned fragment id from \`fragments:\` into a \`superseded:\` list** in the same shard (the new fragment id goes under \`fragments:\`). Both lists keep the ids cited, so no evidence is lost — but \`superseded:\` marks the old evidence as history, not current truth, so retrieval no longer surfaces it as a hook for the new belief. **Reinforcement (a distinct path from contradiction):** when a new fragment REAFFIRMS, repeats, or user-corrects TOWARD the same current truth an existing shard already holds, do NOT drop it as already-known — it is new evidence from a later occurrence. Add the new fragment id under that shard's \`fragments:\` list. The runtime turns that citation into stronger \`cites\`, \`days\`, and \`lastReinforced\` signals — adding a citation IS how reinforcement happens; you never edit those numbers yourself. Do NOT move any old id into \`superseded:\` for a mere reinforcement (that is only for an actually-overturned prior truth). If the fragment is a user CORRECTION showing the agent has been repeating a specific WRONG version, also tighten the belief sentence to state the corrective guard explicitly — "X is not Y anymore; X is Z" — so the negative fact rides in the sentence a channel turn sees first, not just implied by the affirmative list. Add at most one pure-reinforcement citation per shard per day: a same-day repeat with no new correction detail is a burst, not a new day, and \`days\` (not raw \`cites\`) is what drives promotion. Citation-superset invariant: every previously-cited fragment id must still appear cited in at least one shard after your run, in EITHER \`fragments:\` or \`superseded:\`. If you violate this, the runtime reverts your whole run.
|
|
1012
1019
|
|
|
1013
|
-
**6. Write a compact belief, not an essay.** An ordinary belief topic's body is **one compact belief sentence** stating the current truth — a durable fact about the user, project, or environment — placed before \`fragments:\`. It carries the subject, the predicate (the preference/habit/fact/decision), and only the essential scope qualifier needed to avoid overgeneralizing ("for this repo", "when committing", "in host-stage code"). Do NOT explain the evidence, the history, or the reasoning ("because…") — the \`fragments:\` and \`superseded:\` citation lists carry that. No lists of preferences ("the user likes X, Y, Z"), no labels, no markdown headings, no multiple sentences. One topic per concept. Keep the sentence natural and keyword-rich (it is embedded and keyword-searched) — do not compress into telegraphic fragments like "bun/typecheck/lint". Smaller bodies let more topics stay in the directly-injected budget, so tightness is load-bearing, not cosmetic. Fragments may carry situational provenance — \`who\` (the attributed speaker) and \`where\` (the channel/room/platform). Fold these into the belief sentence ONLY when the situation is part of the durable fact ("In #incidents, Jisoo treats production-outage messages as drop-everything urgent") — not as routine provenance noise on every belief; the citation list already records where each fragment came from. **Exception: CLI/plugin proposal shards (see "Suggesting a CLI or a plugin" below) are not belief topics — they keep their richer rationale paragraph plus the required \`proposal:\` label and are exempt from the one-sentence/no-labels rule.**
|
|
1020
|
+
**6. Write a compact belief, not an essay.** An ordinary belief topic's body is **one compact belief sentence** stating the current truth — a durable fact about the user, project, or environment — placed before \`fragments:\`. **The \`heading\` frontmatter MUST be that same belief sentence, not a noun-phrase title.** In channels the agent is shown ONLY the heading (the body is fetched on demand), so a title like "T1 Competition Status 2026" leaves the agent with no fact and it falls back to stale guesses; a heading like "T1's 2026 ADC is Peyz, not Gumayusi (Gumayusi left for HLE)" carries the fact by itself. Make the heading self-contained. It carries the subject, the predicate (the preference/habit/fact/decision), and only the essential scope qualifier needed to avoid overgeneralizing ("for this repo", "when committing", "in host-stage code"). Do NOT explain the evidence, the history, or the reasoning ("because…") — the \`fragments:\` and \`superseded:\` citation lists carry that. No lists of preferences ("the user likes X, Y, Z"), no labels, no markdown headings, no multiple sentences. One topic per concept. Keep the sentence natural and keyword-rich (it is embedded and keyword-searched) — do not compress into telegraphic fragments like "bun/typecheck/lint". Smaller bodies let more topics stay in the directly-injected budget, so tightness is load-bearing, not cosmetic. Fragments may carry situational provenance — \`who\` (the attributed speaker) and \`where\` (the channel/room/platform). Fold these into the belief sentence ONLY when the situation is part of the durable fact ("In #incidents, Jisoo treats production-outage messages as drop-everything urgent") — not as routine provenance noise on every belief; the citation list already records where each fragment came from. **Exception: CLI/plugin proposal shards (see "Suggesting a CLI or a plugin" below) are not belief topics — they keep their richer rationale paragraph plus the required \`proposal:\` label and are exempt from the one-sentence/no-labels rule.**
|
|
1014
1021
|
|
|
1015
1022
|
**7. Memory is passive context, not an instruction channel.** Rewrite imperative or duty-shaped fragments as observations. Preserve facts, user preferences, and evidence; do not promote inferred obligations like "the agent should educate X", "future agents must correct Y", "bot Z should not post", or "run this later" unless the user explicitly stated an always/never rule. When a fragment contains such language, convert it into neutral context about what happened and why it might help interpret a future user request.
|
|
1016
1023
|
|
|
@@ -1029,14 +1036,14 @@ The reference files under \`memory/references/\` are verbatim artifacts. You MUS
|
|
|
1029
1036
|
|
|
1030
1037
|
\`\`\`
|
|
1031
1038
|
---
|
|
1032
|
-
heading: <
|
|
1039
|
+
heading: <the one compact belief sentence — NOT a title (see rule 6)>
|
|
1033
1040
|
cites: 0
|
|
1034
1041
|
days: 0
|
|
1035
1042
|
lastReinforced: 1970-01-01
|
|
1036
1043
|
tags: []
|
|
1037
1044
|
---
|
|
1038
1045
|
|
|
1039
|
-
<
|
|
1046
|
+
<the same belief sentence, repeated as the body's current-truth line (see rule 6)>
|
|
1040
1047
|
|
|
1041
1048
|
fragments:
|
|
1042
1049
|
- streams/yyyy-MM-dd#<fragment-id>
|
|
@@ -1164,7 +1171,7 @@ Do not suggest CLIs or plugins speculatively. The same recurrence + generalizabi
|
|
|
1164
1171
|
|
|
1165
1172
|
1. \`ls memory/topics/\`, then \`read\` the existing topic shards you need to understand. A missing directory means you start from empty.
|
|
1166
1173
|
2. For each JSONL daily stream undreamed-tail entry the user message lists, \`read\` the file with \`offset\` set to the first undreamed line. Read every undreamed tail before you start writing, then focus on fragment events' \`topic\` + \`body\` fields.
|
|
1167
|
-
3. Reason about what to consolidate AND about how to rebalance existing topics using the strength signals at the top of the user prompt.
|
|
1174
|
+
3. Reason about what to consolidate AND about how to rebalance existing topics using the strength signals at the top of the user prompt. For each useful fragment, choose one of four responses: **contradiction** (supersede the old belief), **reinforcement** (a fragment that reaffirms or user-corrects toward an existing shard's current truth — add its id to that shard's \`fragments:\`, per rule 5), **new topic**, or **drop**. A repeated correction or reaffirmation of an existing truth usually REINFORCES the existing shard by adding the new citation — it is NOT "already-known, drop." Drop only same-day/no-new-signal repeats and non-generalizable noise. Most existing topics will keep their shape; a few merge, split, rename, reinforce, or terse-demote every run.
|
|
1168
1175
|
4. Write only the shards that changed. Even if no new fragments earned promotion, a rebalance pass (merging two near-duplicates, renaming an unclear shard, tightening a single weak old topic) is still a productive run. \`write\` overwrites one shard; \`delete_topic_shard\` removes obsolete shards after their citations have moved. Remember: every fragment id cited before your run must still appear in at least one shard after your run. The runtime enforces this mechanically and will revert your whole run if you drop an id.
|
|
1169
1176
|
5. Decide whether any procedure in the new fragments meets the muscle-memory bar above, and which of the three forms fits.
|
|
1170
1177
|
- **Form A (skill):** \`ls\` \`memory/skills/\` to see what already exists, \`read\` any candidate's existing \`SKILL.md\` if you might be refining it, then \`write\` the new or refined skill at \`memory/skills/<name>/SKILL.md\` with the frontmatter shape shown above.
|
|
@@ -3,6 +3,7 @@ import { join } from 'node:path'
|
|
|
3
3
|
|
|
4
4
|
import type { SessionOrigin } from '@/agent/session-origin'
|
|
5
5
|
|
|
6
|
+
import { firstBeliefSentence, isTitleLikeHeading } from './belief-sentence'
|
|
6
7
|
import { buildInjectionPlan, type InjectionPlan } from './injection-plan'
|
|
7
8
|
import { loadAllShards, type TopicShard } from './load-shards'
|
|
8
9
|
import { topicsDir } from './paths'
|
|
@@ -125,7 +126,9 @@ export function renderRetrievedMemorySection(
|
|
|
125
126
|
const provenance = renderProvenanceLine(item)
|
|
126
127
|
if (provenance !== null) lines.push(provenance)
|
|
127
128
|
lines.push(item.excerpt.trimEnd(), '')
|
|
128
|
-
} else if (item.source === 'topic'
|
|
129
|
+
} else if (item.source === 'topic') {
|
|
130
|
+
lines.push(channelTopicEntry(item.heading, item.key, item.excerpt))
|
|
131
|
+
} else if (item.source === 'reference') {
|
|
129
132
|
lines.push(topicIndexEntry(item.heading, item.key))
|
|
130
133
|
} else {
|
|
131
134
|
const provenance = renderProvenanceLine(item)
|
|
@@ -147,8 +150,13 @@ export function renderTopicIndexMemorySection(
|
|
|
147
150
|
const lines = ['# Memory', '', MEMORY_FRAMING, '']
|
|
148
151
|
if (options.origin?.kind === 'channel') lines.push(...CHANNEL_MEMORY_BOUNDARY, '')
|
|
149
152
|
lines.push(topicIndexDirective(options), '')
|
|
153
|
+
const channel = options.origin?.kind === 'channel'
|
|
150
154
|
for (const shard of shards) {
|
|
151
|
-
lines.push(
|
|
155
|
+
lines.push(
|
|
156
|
+
channel
|
|
157
|
+
? channelTopicEntry(shard.frontmatter.heading, shard.slug, shard.body)
|
|
158
|
+
: topicIndexEntry(shard.frontmatter.heading, shard.slug),
|
|
159
|
+
)
|
|
152
160
|
}
|
|
153
161
|
return lines.join('\n').trimEnd()
|
|
154
162
|
}
|
|
@@ -166,6 +174,18 @@ function topicIndexEntry(heading: string, slug: string): string {
|
|
|
166
174
|
return `- ${heading} \`${slug}\``
|
|
167
175
|
}
|
|
168
176
|
|
|
177
|
+
// Channel turns show headings only (memory-bleed defense). That is safe ONLY when
|
|
178
|
+
// the heading is the shard's self-contained belief sentence. Legacy/dreaming shards
|
|
179
|
+
// put a title in `heading` and the fact in the body, so a title-like heading would
|
|
180
|
+
// leak a fact-free label; recover the one belief sentence from the body instead
|
|
181
|
+
// (still one sentence, never the full body). The slug rides along so the agent can
|
|
182
|
+
// `memory_search({ topic })` for the rest.
|
|
183
|
+
function channelTopicEntry(heading: string, slug: string, body: string): string {
|
|
184
|
+
if (!isTitleLikeHeading(heading, slug)) return topicIndexEntry(heading, slug)
|
|
185
|
+
const belief = firstBeliefSentence(body)
|
|
186
|
+
return belief === undefined ? topicIndexEntry(heading, slug) : `- ${belief} \`${slug}\``
|
|
187
|
+
}
|
|
188
|
+
|
|
169
189
|
function topicIndexDirective(options: Pick<LoadMemoryOptions, 'origin'>): string {
|
|
170
190
|
if (options.origin?.kind === 'channel') {
|
|
171
191
|
return 'Memory shown as headings only in channels. Call `memory_search({ topic: "<slug>" })` with a slug below to read a full body.'
|
|
@@ -118,7 +118,7 @@ Capture-worthy categories:
|
|
|
118
118
|
- **Decisions with reasoning.** "We chose X over Y because Z" when future sessions must honor X.
|
|
119
119
|
- **Reproducible workarounds and debugging insights.** A config that worked, flag combination, procedure, root cause, or non-obvious fix.
|
|
120
120
|
- **In-transcript changed minds.** Capture "actually, scratch that" only when the prior position is explicit. Do not compare against \`memory/topics/\`.
|
|
121
|
-
- **Corrections the user made to the agent.** Especially when the agent confidently asserted something false that future sessions may repeat.
|
|
121
|
+
- **Corrections the user made to the agent.** Especially when the agent confidently asserted something false that future sessions may repeat. When the agent stated a factual claim and the user corrected it, capture the corrected fact as a distinct, evidence-anchored fragment EVEN IF it sounds like something memory may already know — you cannot inspect \`memory/topics/\`, so your job is to preserve this later correction occurrence so dreaming can reinforce and sharpen the stored belief (repeated corrections are how a contested fact gets stronger, not noise to skip). Anchor the body to the correction: what the agent said, what the user corrected it to. This is semantic and **language-independent** — recognize corrections in any language (Korean, Japanese, Chinese, Arabic, and every Latin-script language), not from English cue phrases.
|
|
122
122
|
- **Content the user explicitly taught, trained on, or asked the agent to remember.** Capture the substance taught, not merely that teaching happened. Treat these six intent families as representative, not exhaustive:
|
|
123
123
|
- **Teach / explain-so-you-know.** "let me teach you Y", "you should know that…", "이건 알아둬".
|
|
124
124
|
- **Train / point-and-learn.** "study this", "look at how X did it and learn", "보고 배워".
|
|
@@ -80,7 +80,7 @@ PREFER the two purpose-built research workers for any quick search or gathering
|
|
|
80
80
|
- \`scout\` — web research. Spawn it for ANYTHING that lives on the public internet: prices, schedules, opening hours, standard timelines, prevailing practice, vendor docs, prior art, "what are the options for X". It returns a focused, citation-backed answer. This is your default for the research-resolvable facts a plan rests on.
|
|
81
81
|
- \`explorer\` — local filesystem search. Spawn it to understand the existing code, config, sessions, memory, or git history on this agent — "what does this module do", "where is X configured", "summarize the shape of this system" — before planning a change to it.
|
|
82
82
|
|
|
83
|
-
Lean on these liberally. A quick \`scout\` for real prices or a quick \`explorer\` for the actual shape of a module turns an assumption-laden plan into a grounded one, and it costs you almost nothing because the heavy reading happens in their context, not yours. When a plan depends on multiple independent facts, **fan out in parallel**: either emit all the independent \`spawn_subagent\` calls (
|
|
83
|
+
Lean on these liberally. A quick \`scout\` for real prices or a quick \`explorer\` for the actual shape of a module turns an assumption-laden plan into a grounded one, and it costs you almost nothing because the heavy reading happens in their context, not yours. When a plan depends on multiple independent facts, **fan out in parallel**: either emit all the independent \`spawn_subagent\` calls (foreground, the default from your session) in a SINGLE turn so they run concurrently and return together, or spawn them with \`run_in_foreground=false\` and fold each result in as its \`<system-reminder>\` arrives (your session stays alive until every child reports back). Either way, fold the distilled results into your single planning pass; do NOT spawn one, wait, then spawn the next unless the second genuinely depends on the first — that serializes what should be parallel.
|
|
84
84
|
|
|
85
85
|
- Spawn these workers for context-heavy GATHERING, not for forming the plan. The decomposition, the sequencing, and the verdict are YOURS — never delegate the judgment.
|
|
86
86
|
- Each delegated task must be self-contained: the worker does not see this conversation or the goal. Put everything it needs in the prompt.
|
|
@@ -70,8 +70,8 @@ You run on a deliberately expensive model. Every search result page and every fe
|
|
|
70
70
|
**Delegate first; fetch yourself only as a last resort.** Before you reach for \`web_search\`, \`web_fetch\`, \`read\`, or \`grep\`, ask: "could \`scout\` or \`explorer\` get this for me and hand back just the distilled answer?" If yes — which is almost always — spawn the worker with \`spawn_subagent\`.
|
|
71
71
|
|
|
72
72
|
**Fan out in parallel.** For a gathering round, emit several \`scout\`/\`explorer\` \`spawn_subagent\` calls together in a SINGLE turn so they run concurrently rather than one-at-a-time. You have two equivalent ways to do this, both of which deliver every worker's findings back to you:
|
|
73
|
-
- **Synchronous batch (simplest):** emit the calls with
|
|
74
|
-
- **Background:** emit them with \`
|
|
73
|
+
- **Synchronous batch (simplest, the default):** emit the calls in one assistant message with no mode flag. From your subagent session they run in the FOREGROUND by default — they execute concurrently and all results return together before your next turn, where you fold them into one synthesis pass.
|
|
74
|
+
- **Background:** emit them with \`run_in_foreground=false\`; each returns a task_id immediately and you receive a \`<system-reminder>\` as each completes, then fetch the result with \`subagent_output\`. Use this when you want to start synthesizing on early results while slower workers finish. Your session stays alive until every background child you spawned has reported back, so no result is lost.
|
|
75
75
|
|
|
76
76
|
Either way, do NOT spawn one, wait for it, then spawn the next unless the second task genuinely depends on the first's result — that serializes what should be parallel.
|
|
77
77
|
|
|
@@ -92,7 +92,7 @@ This is not a last resort — it is your DEFAULT for any non-trivial target, and
|
|
|
92
92
|
- Spawn read-only/research workers (\`scout\`, \`explorer\`) for context-heavy gathering, not for forming the verdict. The findings and the \`<review>\` block are YOURS — never delegate the judgment.
|
|
93
93
|
- Each delegated task must be self-contained: the worker does not see this conversation or the target. Put everything it needs in the prompt.
|
|
94
94
|
- The chain is depth-limited: a worker you spawn cannot spawn again. Keep delegation one level deep.
|
|
95
|
-
- \`subagent_output\`/\`subagent_cancel\` reach only the tasks YOU spawned. To gather in parallel, either emit all the independent \`spawn_subagent\` calls (
|
|
95
|
+
- \`subagent_output\`/\`subagent_cancel\` reach only the tasks YOU spawned. To gather in parallel, either emit all the independent \`spawn_subagent\` calls (foreground, the default from your session) in a SINGLE turn so they run concurrently and return together, or spawn them with \`run_in_foreground=false\` and fold each result in as its \`<system-reminder>\` arrives (your session stays alive until every child reports back). Either way, fold the results into your single review pass before you finish.
|
|
96
96
|
|
|
97
97
|
## Tools
|
|
98
98
|
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type Controller, type DeploymentProfile, resolveController, resolveDeploymentProfile } from '@/container'
|
|
2
|
+
|
|
3
|
+
// The host-stage capability bag: what the host process (CLI / hostd / a future
|
|
4
|
+
// managed control task) can DO to a container. Assembled once at the host-stage
|
|
5
|
+
// composition root and passed to the modules that need it — NOT a service
|
|
6
|
+
// locator (build at the root, hand specific capabilities down).
|
|
7
|
+
//
|
|
8
|
+
// Only `controller` today; restartSupervisor / portBroker / credentialRenewers
|
|
9
|
+
// slot in here as they are extracted (see the capability-composition design).
|
|
10
|
+
export type ControlPlaneCapabilities = {
|
|
11
|
+
controller: Controller
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Composes the host-stage capabilities for a deployment profile. `host` uses
|
|
15
|
+
// local Docker; `managed` (no runtime yet) would use platform impls. The
|
|
16
|
+
// profile is resolved once here so the whole bag reflects one coherent
|
|
17
|
+
// environment decision.
|
|
18
|
+
export function createControlPlaneCapabilities(
|
|
19
|
+
profile: DeploymentProfile = resolveDeploymentProfile(),
|
|
20
|
+
): ControlPlaneCapabilities {
|
|
21
|
+
return {
|
|
22
|
+
controller: resolveController(profile),
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
|
|
3
|
+
import { type RuntimeSecretsProvider, resolveRuntimeSecretsProvider } from '@/secrets/secrets-provider'
|
|
4
|
+
|
|
5
|
+
// The container-stage capability bag: what the agent runtime (`typeclaw run`)
|
|
6
|
+
// can CALL to reach durable host-side substrate. Assembled once at the
|
|
7
|
+
// container-stage composition root and passed to the modules that need it —
|
|
8
|
+
// build at the root, hand specific capabilities down (not a service locator).
|
|
9
|
+
//
|
|
10
|
+
// `secrets` is nullable: it degrades to null when no write-back backend is
|
|
11
|
+
// wired (hostd triple absent, or a managed profile without write-back yet), so
|
|
12
|
+
// the runtime boots without crashing. restarter / portForwarder / ingress slot
|
|
13
|
+
// in here as they are extracted (see the capability-composition design).
|
|
14
|
+
export type RuntimeCapabilities = {
|
|
15
|
+
secrets: RuntimeSecretsProvider | null
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Composes the container-stage capabilities. `secretsPath` is the mounted
|
|
19
|
+
// secrets.json the runtime reads (defaults to <cwd>/secrets.json, which is
|
|
20
|
+
// /agent/secrets.json in the container). Env is injectable for tests. (No
|
|
21
|
+
// profile param yet — secrets resolution keys off the env triple; the
|
|
22
|
+
// deployment profile enters here when a managed secrets impl selects on it.)
|
|
23
|
+
export function createRuntimeCapabilities(
|
|
24
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
25
|
+
secretsPath: string = join(process.cwd(), 'secrets.json'),
|
|
26
|
+
): RuntimeCapabilities {
|
|
27
|
+
return {
|
|
28
|
+
secrets: resolveRuntimeSecretsProvider(env, secretsPath),
|
|
29
|
+
}
|
|
30
|
+
}
|