@botlearn-course/daemon 0.0.28 → 0.0.29-beta.1
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/dist/run-dispatcher.js +7 -0
- package/dist/runtime-activity.d.ts +21 -0
- package/dist/runtime-activity.js +5 -0
- package/dist/runtimes/deepseek-tui.js +6 -1
- package/dist/runtimes/engine.d.ts +4 -1
- package/dist/runtimes/engine.js +18 -8
- package/dist/runtimes/index.js +12 -1
- package/dist/runtimes/native-tool-blocks.d.ts +3 -0
- package/dist/runtimes/native-tool-blocks.js +98 -0
- package/dist/runtimes/pi-agent.js +4 -1
- package/dist/runtimes/tool-semantics.d.ts +12 -0
- package/dist/runtimes/tool-semantics.js +134 -0
- package/dist/tool-observation.d.ts +2 -1
- package/dist/tool-observation.js +4 -2
- package/dist/types.d.ts +3 -0
- package/package.json +1 -1
package/dist/run-dispatcher.js
CHANGED
|
@@ -287,12 +287,14 @@ export class RunDispatcher {
|
|
|
287
287
|
: {}),
|
|
288
288
|
};
|
|
289
289
|
};
|
|
290
|
+
let runtimeMetadata = { type: runtimeId, adapter_version: "1" };
|
|
290
291
|
const send = async (event) => {
|
|
291
292
|
if (serverTerminal)
|
|
292
293
|
return;
|
|
293
294
|
seq += 1;
|
|
294
295
|
const outgoing = {
|
|
295
296
|
...event,
|
|
297
|
+
payload: { ...event.payload, runtime_meta: { ...runtimeMetadata } },
|
|
296
298
|
trace_id: traceId,
|
|
297
299
|
seq,
|
|
298
300
|
event_id: event.event_id ?? randomUUID(),
|
|
@@ -828,6 +830,11 @@ export class RunDispatcher {
|
|
|
828
830
|
file: async (file) => {
|
|
829
831
|
await this.client.postFiles(runId, [file]);
|
|
830
832
|
},
|
|
833
|
+
runtimeMetadata: async (metadata) => {
|
|
834
|
+
runtimeMetadata = metadata;
|
|
835
|
+
await send({ type: "run.block", payload: { schema_version: AGENT_STREAM_SCHEMA_VERSION,
|
|
836
|
+
kind: "status", runtime: runtime.id, phase: "executing" } });
|
|
837
|
+
},
|
|
831
838
|
runtimeSession: async (sessionId) => {
|
|
832
839
|
activeNativeSessionId = sessionId;
|
|
833
840
|
this.persistentSession?.persistNativeSession(sessionId);
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Versioned, provider-neutral display facts. Native payloads never cross this boundary. */
|
|
2
|
+
export interface RuntimeMetadata {
|
|
3
|
+
type: string;
|
|
4
|
+
version?: string;
|
|
5
|
+
adapter_version: '1';
|
|
6
|
+
}
|
|
7
|
+
export declare const TOOL_ACTIONS: readonly ["read", "write", "edit", "list", "search", "execute", "validate", "browse_web", "inspect_git", "delegate", "download", "upload", "prepare_attachment", "operate", "discover_tools", "load_skill", "plan", "request_input"];
|
|
8
|
+
export type ToolAction = typeof TOOL_ACTIONS[number];
|
|
9
|
+
export type ActivityState = 'queued' | 'paused' | 'running' | 'waiting' | 'completed' | 'failed' | 'cancelled' | 'unknown';
|
|
10
|
+
export interface RuntimeActivity {
|
|
11
|
+
schema_version: 'runtime-activity/1';
|
|
12
|
+
kind: 'tool' | 'subtask';
|
|
13
|
+
operation: ToolAction | 'start' | 'wait' | 'status' | 'peek' | 'message' | 'followup' | 'interrupt' | 'cancel' | 'roster' | 'claim';
|
|
14
|
+
call_id?: string;
|
|
15
|
+
outcome: 'pending' | 'success' | 'failed' | 'timed_out' | 'cancelled' | 'unknown';
|
|
16
|
+
targets: {
|
|
17
|
+
id: string;
|
|
18
|
+
state: ActivityState;
|
|
19
|
+
wait_reason?: 'model' | 'tool' | 'subtask' | 'user';
|
|
20
|
+
}[];
|
|
21
|
+
}
|
|
@@ -8,6 +8,7 @@ import { prepareRuntimeSkillsHome, RUNTIME_SKILLS_RELATIVE_PATH, } from "../runt
|
|
|
8
8
|
import { startCourseSkillsMcpServer, } from "../mcp/course-skills-server.js";
|
|
9
9
|
import { sanitizeRuntimeFailureText } from "../redaction.js";
|
|
10
10
|
import { runtimeChildEnv, runtimeChildLaunch } from "../runtime-env.js";
|
|
11
|
+
import { ToolSemantics } from "./tool-semantics.js";
|
|
11
12
|
import { readCommandVersion, resolveCommandOnPath } from "./probe.js";
|
|
12
13
|
import { DEEPSEEK_TUI_ZH_CN_BASE_PROMPT_VERSION, deepseekRuntimeSystemPrompt, usesChineseDeepseekBasePrompt, } from "./deepseek-tui-base-prompt.js";
|
|
13
14
|
import { adaptDeepseekProgressStarted, cleanupProgressMcpConfig, createDeepseekProgressState, createProgressMcpConfig, deepseekProgressDispositions, isDeepseekProgressCompletion, progressMcpAutoInjectionSupported, progressSystemContext, } from "./progress.js";
|
|
@@ -220,6 +221,9 @@ export class DeepseekTuiAdapter {
|
|
|
220
221
|
: POOL_KEY;
|
|
221
222
|
releaseTurn = await acquireDeepseekTurn(turnQueueKey, turnAbort.signal);
|
|
222
223
|
handle = await this.acquireHandle(opts, turnAbort.signal);
|
|
224
|
+
const version = this.explicitServerUrl ? undefined
|
|
225
|
+
: readCommandVersion(this.resolveBinary(), [], { env: opts.env })?.match(/\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?/)?.[0];
|
|
226
|
+
await opts.onRuntimeMetadata?.({ type: this.id, adapter_version: "1", ...(version ? { version } : {}) });
|
|
223
227
|
if (turnAbort.signal.aborted)
|
|
224
228
|
throw abortReason(turnAbort.signal);
|
|
225
229
|
handle.inFlight += 1;
|
|
@@ -862,6 +866,7 @@ export class DeepseekTuiAdapter {
|
|
|
862
866
|
}
|
|
863
867
|
text += chunk;
|
|
864
868
|
};
|
|
869
|
+
const toolSemantics = new ToolSemantics(true);
|
|
865
870
|
const emit = (eventName, payload) => {
|
|
866
871
|
// 其他 turn 的事件(并发轮次、历史重放)一律过滤。
|
|
867
872
|
const eventTurnId = stringField(payload, "turn_id") ?? stringField(payload?.payload, "turn_id");
|
|
@@ -907,7 +912,7 @@ export class DeepseekTuiAdapter {
|
|
|
907
912
|
? null
|
|
908
913
|
: normalizeDeepseekEvent(eventName, payload, seq);
|
|
909
914
|
if (block)
|
|
910
|
-
opts.onBlock?.(block);
|
|
915
|
+
opts.onBlock?.(block.kind === "progress" ? block : toolSemantics.normalize(block));
|
|
911
916
|
// report_progress is non-authoritative telemetry: its tool failure never fails the task.
|
|
912
917
|
const extractedError = suppressProgressResult || courseSkillCompleted
|
|
913
918
|
? undefined
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { RuntimeActivity, RuntimeMetadata } from "../runtime-activity.js";
|
|
1
2
|
import { type CourseRuntime, type RuntimeCompletionReason, type RuntimeFailureSummary, type RuntimeProgressDispositions, type RuntimeUsage, type RunStartPayload } from "../types.js";
|
|
2
3
|
import type { Logger } from "../log.js";
|
|
3
4
|
import type { ProgressReport } from "../mcp/report-progress.js";
|
|
@@ -7,8 +8,9 @@ import type { PreparedRuntimeSkillProvider, RuntimeSkillEvent } from "../runtime
|
|
|
7
8
|
* 由 wrapEngineAdapter 折叠成对外的 CourseRuntime(sink 语义)。
|
|
8
9
|
*/
|
|
9
10
|
export interface ContentStreamBlock {
|
|
11
|
+
activity?: RuntimeActivity;
|
|
10
12
|
raw: unknown;
|
|
11
|
-
kind: "assistant_text" | "tool_use" | "tool_result" | "system" | "thinking" | "other";
|
|
13
|
+
kind: "assistant_text" | "tool_use" | "tool_result" | "system" | "thinking" | "other" | "error";
|
|
12
14
|
seq: number;
|
|
13
15
|
/** Assistant-visible text only. Provider raw payloads must never be used as browser text. */
|
|
14
16
|
text?: string;
|
|
@@ -51,6 +53,7 @@ export interface EngineRunOptions {
|
|
|
51
53
|
/** Final backend-owned prompt for managed execution; applied verbatim. */
|
|
52
54
|
systemPrompt?: string;
|
|
53
55
|
onBlock?: (block: StreamBlock) => void;
|
|
56
|
+
onRuntimeMetadata?: (metadata: RuntimeMetadata) => Promise<void>;
|
|
54
57
|
onStatus?: (event: RuntimeStatusEvent) => void;
|
|
55
58
|
env?: NodeJS.ProcessEnv;
|
|
56
59
|
/** Control-side binding. Runtime adapters must not copy its credential into child env. */
|
package/dist/runtimes/engine.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { nativeToolBlocks } from "./native-tool-blocks.js";
|
|
2
|
+
import { ToolSemantics } from "./tool-semantics.js";
|
|
1
3
|
import { validateRuntimePrompt } from "../runtime-prompt.js";
|
|
2
4
|
import { extractReasoningText } from "../trace-projection.js";
|
|
3
5
|
import { RuntimeBlockBuffer } from "./block-buffer.js";
|
|
@@ -147,6 +149,7 @@ const BLOCK_KIND_MAP = {
|
|
|
147
149
|
thinking: "thinking",
|
|
148
150
|
system: "status",
|
|
149
151
|
other: "status",
|
|
152
|
+
error: "error",
|
|
150
153
|
};
|
|
151
154
|
/** 把内部 EngineAdapter 包装成对外 CourseRuntime。 */
|
|
152
155
|
export function wrapEngineAdapter(id, engine, opts) {
|
|
@@ -215,6 +218,7 @@ export function wrapEngineAdapter(id, engine, opts) {
|
|
|
215
218
|
blocks.add(block);
|
|
216
219
|
}
|
|
217
220
|
};
|
|
221
|
+
const genericTools = new ToolSemantics(false);
|
|
218
222
|
let result;
|
|
219
223
|
try {
|
|
220
224
|
result = await engine.run({
|
|
@@ -235,6 +239,7 @@ export function wrapEngineAdapter(id, engine, opts) {
|
|
|
235
239
|
...(systemContext !== undefined ? { systemContext } : {}),
|
|
236
240
|
...(serverPrompt !== undefined
|
|
237
241
|
? { systemPrompt: serverPrompt, systemContext: serverPrompt } : {}),
|
|
242
|
+
onRuntimeMetadata: metadata => sink.runtimeMetadata?.(metadata) ?? Promise.resolve(),
|
|
238
243
|
onBlock: (block) => {
|
|
239
244
|
if (block.kind === "progress") {
|
|
240
245
|
queueBlock({
|
|
@@ -245,14 +250,19 @@ export function wrapEngineAdapter(id, engine, opts) {
|
|
|
245
250
|
});
|
|
246
251
|
return;
|
|
247
252
|
}
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
253
|
+
for (let normalized of nativeToolBlocks(id, block)) {
|
|
254
|
+
if (!normalized.activity)
|
|
255
|
+
normalized = genericTools.normalize(normalized);
|
|
256
|
+
const kind = BLOCK_KIND_MAP[normalized.kind] ?? "status";
|
|
257
|
+
queueBlock({
|
|
258
|
+
kind,
|
|
259
|
+
raw: normalized.raw,
|
|
260
|
+
...(normalized.activity ? { activity: normalized.activity } : {}),
|
|
261
|
+
...(normalized.text !== undefined ? { text: normalized.text } : {}),
|
|
262
|
+
...(normalized.name !== undefined ? { name: normalized.name } : {}),
|
|
263
|
+
...(normalized.status !== undefined ? { status: normalized.status } : {}),
|
|
264
|
+
});
|
|
265
|
+
}
|
|
256
266
|
},
|
|
257
267
|
onStatus: (event) => {
|
|
258
268
|
consoleLogger.debug(`${id} status`, { kind: event.kind, phase: event.phase });
|
package/dist/runtimes/index.js
CHANGED
|
@@ -40,7 +40,18 @@ export function createRuntime(id) {
|
|
|
40
40
|
const mod = getRuntimeModule(id);
|
|
41
41
|
if (!mod)
|
|
42
42
|
throw new Error(`unknown runtime: ${id}`);
|
|
43
|
-
|
|
43
|
+
const runtime = mod.create();
|
|
44
|
+
return {
|
|
45
|
+
...runtime,
|
|
46
|
+
async run(run, sink, signal) {
|
|
47
|
+
if (!['deepseek-tui', 'pi-agent'].includes(id)) {
|
|
48
|
+
const probe = await mod.probe().catch(() => ({ available: false }));
|
|
49
|
+
const version = probe.version?.match(/\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?/)?.[0];
|
|
50
|
+
await sink.runtimeMetadata?.({ type: id, adapter_version: '1', ...(version ? { version } : {}) });
|
|
51
|
+
}
|
|
52
|
+
return runtime.run(run, sink, signal);
|
|
53
|
+
},
|
|
54
|
+
};
|
|
44
55
|
}
|
|
45
56
|
export async function detectRuntimes(opts = {}) {
|
|
46
57
|
const out = [];
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { toolCallId } from '../tool-observation.js';
|
|
2
|
+
const object = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : {};
|
|
3
|
+
const ACP_KIND_TOOL_NAMES = {
|
|
4
|
+
read: 'read', edit: 'edit', delete: 'edit', execute: 'exec_command',
|
|
5
|
+
search: 'file_search', fetch: 'fetch_url',
|
|
6
|
+
};
|
|
7
|
+
/** Provider envelopes may contain several calls; normalize before call correlation. */
|
|
8
|
+
export function nativeToolBlocks(runtime, block) {
|
|
9
|
+
const raw = object(block.raw);
|
|
10
|
+
if (runtime === 'codex') {
|
|
11
|
+
const item = object(raw.item);
|
|
12
|
+
if (item.type === 'collab_tool_call') {
|
|
13
|
+
const operations = {
|
|
14
|
+
spawn_agent: 'start', send_input: 'message', wait: 'wait', close_agent: 'cancel',
|
|
15
|
+
};
|
|
16
|
+
const states = { pending_init: 'queued', running: 'running',
|
|
17
|
+
interrupted: 'paused', completed: 'completed', errored: 'failed', shutdown: 'cancelled', not_found: 'unknown' };
|
|
18
|
+
if (typeof item.tool !== 'string' || !Object.hasOwn(operations, item.tool))
|
|
19
|
+
return [{ ...block, kind: raw.type === 'item.completed' ? 'tool_result' : 'tool_use', name: 'unknown_collaboration', status: undefined }];
|
|
20
|
+
const kind = raw.type === 'item.completed' ? 'tool_result' : 'tool_use';
|
|
21
|
+
const callId = toolCallId({ item });
|
|
22
|
+
const nativeStates = object(item.agents_states);
|
|
23
|
+
const ids = [...new Set([...(Array.isArray(item.receiver_thread_ids) ? item.receiver_thread_ids : []), ...Object.keys(nativeStates)])]
|
|
24
|
+
.filter((id) => typeof id === 'string' && /^[A-Za-z0-9_.:-]{1,120}$/.test(id));
|
|
25
|
+
return [{ ...block, kind, name: 'collab_tool_call',
|
|
26
|
+
status: item.status === 'failed' ? 'error' : item.status === 'completed' ? 'completed' : undefined,
|
|
27
|
+
activity: { schema_version: 'runtime-activity/1', kind: 'subtask', operation: operations[item.tool],
|
|
28
|
+
...(callId ? { call_id: callId } : {}),
|
|
29
|
+
outcome: kind === 'tool_use' ? 'pending' : item.status === 'failed' ? 'failed' : item.status === 'completed' ? 'success' : 'unknown',
|
|
30
|
+
targets: ids.map(id => {
|
|
31
|
+
const status = object(nativeStates[id]).status;
|
|
32
|
+
return { id, state: typeof status === 'string' && Object.hasOwn(states, status) ? states[status] : 'unknown' };
|
|
33
|
+
}),
|
|
34
|
+
} }];
|
|
35
|
+
}
|
|
36
|
+
if (item.type === 'reasoning' && typeof item.text === 'string')
|
|
37
|
+
return [{ ...block, kind: 'thinking', text: item.text }];
|
|
38
|
+
if (item.type === 'error')
|
|
39
|
+
return [{ ...block, kind: 'error', status: 'error' }];
|
|
40
|
+
if (item.type === 'todo_list')
|
|
41
|
+
return [{ ...block, kind: raw.type === 'item.completed' ? 'tool_result' : 'tool_use',
|
|
42
|
+
name: 'update_plan', status: raw.type === 'item.completed' ? 'completed' : undefined }];
|
|
43
|
+
if (item.type === 'web_search' && raw.type === 'item.completed')
|
|
44
|
+
return [{ ...block, kind: 'tool_result', name: 'web_search', status: 'completed' }];
|
|
45
|
+
}
|
|
46
|
+
if (runtime === 'claude-code' && Array.isArray(raw.message?.content)) {
|
|
47
|
+
const blocks = raw.message.content.flatMap((value) => {
|
|
48
|
+
const c = object(value);
|
|
49
|
+
if (c.type === 'tool_use')
|
|
50
|
+
return [{ kind: 'tool_use', seq: block.seq, name: c.name,
|
|
51
|
+
raw: { tool_call_id: c.id, input: c.input } }];
|
|
52
|
+
if (c.type === 'tool_result')
|
|
53
|
+
return [{ kind: 'tool_result', seq: block.seq,
|
|
54
|
+
status: c.is_error === true ? 'error' : 'completed', raw: { tool_call_id: c.tool_use_id, output: c.content } }];
|
|
55
|
+
if (c.type === 'text' && raw.type === 'assistant' && typeof c.text === 'string')
|
|
56
|
+
return [{ kind: 'assistant_text', seq: block.seq, text: c.text, raw: c }];
|
|
57
|
+
if (c.type === 'thinking' && typeof c.thinking === 'string')
|
|
58
|
+
return [{ kind: 'thinking', seq: block.seq, text: c.thinking, raw: c }];
|
|
59
|
+
return [];
|
|
60
|
+
});
|
|
61
|
+
return blocks.length ? blocks : [block];
|
|
62
|
+
}
|
|
63
|
+
if (runtime === 'kimi-cli') {
|
|
64
|
+
if (raw.role === 'assistant' && Array.isArray(raw.tool_calls) && raw.tool_calls.length) {
|
|
65
|
+
const text = typeof raw.content === 'string' ? raw.content : Array.isArray(raw.content)
|
|
66
|
+
? raw.content.filter((c) => c?.type === 'text' && typeof c.text === 'string').map((c) => c.text).join('') : '';
|
|
67
|
+
return [...(text ? [{ kind: 'assistant_text', seq: block.seq, text, raw: null }] : []),
|
|
68
|
+
...raw.tool_calls.map(object).map((c) => ({ kind: 'tool_use', seq: block.seq,
|
|
69
|
+
name: c.function?.name, raw: { tool_call_id: c.id, arguments: c.function?.arguments } }))];
|
|
70
|
+
}
|
|
71
|
+
if (raw.role === 'tool')
|
|
72
|
+
return [{ ...block, status: raw.error ? 'error' : 'completed' }];
|
|
73
|
+
}
|
|
74
|
+
if (runtime === 'hermes-agent' || runtime === 'openclaw-acp') {
|
|
75
|
+
const update = object(raw.params?.update ?? raw.update);
|
|
76
|
+
if (['tool_call', 'tool_call_update'].includes(update.sessionUpdate)) {
|
|
77
|
+
const tool = object(update.toolCall ?? update);
|
|
78
|
+
// ACP updates are often progress, not terminal results. Keep the original call active.
|
|
79
|
+
if (update.sessionUpdate === 'tool_call_update' && (tool.status == null || ['pending', 'in_progress'].includes(tool.status)))
|
|
80
|
+
return [];
|
|
81
|
+
return [{ ...block, kind: update.sessionUpdate === 'tool_call' ? 'tool_use' : 'tool_result',
|
|
82
|
+
name: typeof tool.kind === 'string' && Object.hasOwn(ACP_KIND_TOOL_NAMES, tool.kind)
|
|
83
|
+
? ACP_KIND_TOOL_NAMES[tool.kind] : tool.name,
|
|
84
|
+
status: tool.status === 'failed' ? 'error' : tool.status === 'completed' ? 'completed' : undefined,
|
|
85
|
+
raw: { tool_call_id: tool.toolCallId ?? tool.id ?? update.toolCallId, input: tool.rawInput, output: tool.rawOutput } }];
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if (runtime === 'gemini' && ['tool_use', 'tool_result'].includes(raw.type)) {
|
|
89
|
+
return [{ ...block, raw: { tool_call_id: raw.tool_id, input: raw.parameters, output: raw.output },
|
|
90
|
+
status: raw.type === 'tool_result' ? raw.status === 'error' ? 'error' : raw.status === 'success' ? 'completed' : undefined : undefined }];
|
|
91
|
+
}
|
|
92
|
+
if (runtime === 'codex' && block.kind === 'tool_result') {
|
|
93
|
+
const item = object(raw.item);
|
|
94
|
+
return [{ ...block, status: item.status === 'failed' || (typeof item.exit_code === 'number' && item.exit_code !== 0)
|
|
95
|
+
? 'error' : item.status === 'completed' ? 'completed' : undefined }];
|
|
96
|
+
}
|
|
97
|
+
return [block];
|
|
98
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ToolSemantics } from "./tool-semantics.js";
|
|
1
2
|
import { spawn } from "node:child_process";
|
|
2
3
|
import { fileURLToPath } from "node:url";
|
|
3
4
|
import { startCourseSkillsMcpServer } from "../mcp/course-skills-server.js";
|
|
@@ -75,6 +76,8 @@ export class PiAgentAdapter {
|
|
|
75
76
|
if (!binary || (managed ? managedPiVersion() : readCommandVersion(binary, [], { env })) !== PI_AGENT_VERSION) {
|
|
76
77
|
throw new Error(`pi-agent requires @earendil-works/pi-coding-agent@${PI_AGENT_VERSION}`);
|
|
77
78
|
}
|
|
79
|
+
await opts.onRuntimeMetadata?.({ type: this.id, version: PI_AGENT_VERSION, adapter_version: "1" });
|
|
80
|
+
const toolSemantics = new ToolSemantics(false);
|
|
78
81
|
const args = [
|
|
79
82
|
"--mode", "rpc", "--no-approve", "--no-extensions", "--no-skills",
|
|
80
83
|
"--no-prompt-templates", "--no-themes", "--no-context-files",
|
|
@@ -151,7 +154,7 @@ export class PiAgentAdapter {
|
|
|
151
154
|
textBytes += Buffer.byteLength(data.text ?? "");
|
|
152
155
|
if (textBytes > MAX_TEXT_BYTES)
|
|
153
156
|
return fail("pi-agent text exceeded the turn limit");
|
|
154
|
-
opts.onBlock?.({ kind, seq: ++seq, raw: data.raw ?? null, ...data });
|
|
157
|
+
opts.onBlock?.(toolSemantics.normalize({ kind, seq: ++seq, raw: data.raw ?? null, ...data }));
|
|
155
158
|
};
|
|
156
159
|
const onEvent = (event) => {
|
|
157
160
|
if (opts.signal.aborted && event.type === "response" && event.id === "abort") {
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { RuntimeActivity, ToolAction, ActivityState } from '../runtime-activity.js';
|
|
2
|
+
import type { ContentStreamBlock } from './engine.js';
|
|
3
|
+
export declare function toolAction(name: string): ToolAction;
|
|
4
|
+
export declare const CODEWHALE_OPERATIONS: Readonly<Record<string, RuntimeActivity['operation']>>;
|
|
5
|
+
export declare const CODEWHALE_STATES: Readonly<Record<string, ActivityState>>;
|
|
6
|
+
/** Per-turn correlation lives at the native adapter boundary. Never match concurrent calls by name. */
|
|
7
|
+
export declare class ToolSemantics {
|
|
8
|
+
private readonly supportsAgentActions;
|
|
9
|
+
private readonly calls;
|
|
10
|
+
constructor(supportsAgentActions: boolean);
|
|
11
|
+
normalize(block: ContentStreamBlock): ContentStreamBlock;
|
|
12
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { toolCallId } from '../tool-observation.js';
|
|
2
|
+
const ACTIONS = {
|
|
3
|
+
handle_read: 'read', image_analyze: 'read', recall_archive: 'read',
|
|
4
|
+
checklist_write: 'plan', task_list: 'list', code_execution: 'execute',
|
|
5
|
+
rlm_open: 'execute', rlm_eval: 'execute',
|
|
6
|
+
list_mcp_resources: 'list', list_mcp_resource_templates: 'list', tool_search_tool_bm25: 'discover_tools',
|
|
7
|
+
read: 'read', read_file: 'read', 'workspace.read': 'read',
|
|
8
|
+
write: 'write', write_file: 'write', edit: 'edit', edit_file: 'edit', apply_patch: 'edit', fim_edit: 'edit',
|
|
9
|
+
list_dir: 'list', list_directory: 'list', ls: 'list',
|
|
10
|
+
grep: 'search', find: 'search', grep_files: 'search', file_search: 'search',
|
|
11
|
+
command_execution: 'execute', file_change: 'edit',
|
|
12
|
+
bash: 'execute', exec_shell: 'execute', exec_command: 'execute', shell: 'execute',
|
|
13
|
+
run_tests: 'validate', run_verifiers: 'validate', diagnostics: 'validate', validate_data: 'validate', task_gate_run: 'validate',
|
|
14
|
+
web_search: 'browse_web', fetch_url: 'browse_web', web_run: 'browse_web', 'web.run': 'browse_web',
|
|
15
|
+
download_file: 'download', file_download: 'download', 'workspace.download': 'download', download_attachment: 'download',
|
|
16
|
+
upload_file: 'upload', file_upload: 'upload', 'workspace.upload': 'upload',
|
|
17
|
+
prepare_attachment: 'prepare_attachment', materialize_attachment: 'prepare_attachment', input_attachment: 'prepare_attachment',
|
|
18
|
+
tool_search: 'discover_tools', tool_search_tool_regex: 'discover_tools',
|
|
19
|
+
mcp_courseskills_list_skills: 'load_skill', mcp_courseskills_load_skill: 'load_skill', mcp_courseskills_load_reference: 'load_skill',
|
|
20
|
+
load_skill: 'load_skill',
|
|
21
|
+
todo_write: 'plan', update_plan: 'plan', request_user_input: 'request_input',
|
|
22
|
+
};
|
|
23
|
+
export function toolAction(name) {
|
|
24
|
+
return (Object.hasOwn(ACTIONS, name) ? ACTIONS[name] : undefined) ?? (name.startsWith('git_') ? 'inspect_git'
|
|
25
|
+
: /^(exec_shell_|task_shell_)/.test(name) ? 'execute' : 'operate');
|
|
26
|
+
}
|
|
27
|
+
function object(value) {
|
|
28
|
+
if (typeof value === 'string') {
|
|
29
|
+
try {
|
|
30
|
+
return object(JSON.parse(value));
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return {};
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
37
|
+
}
|
|
38
|
+
function field(raw, keys, depth = 0) {
|
|
39
|
+
if (depth > 5)
|
|
40
|
+
return undefined;
|
|
41
|
+
const o = object(raw);
|
|
42
|
+
for (const key of keys)
|
|
43
|
+
if (o[key] !== undefined)
|
|
44
|
+
return o[key];
|
|
45
|
+
for (const key of ['payload', 'raw', 'data', 'tool_call', 'item']) {
|
|
46
|
+
const found = field(o[key], keys, depth + 1);
|
|
47
|
+
if (found !== undefined)
|
|
48
|
+
return found;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function safeId(value) {
|
|
52
|
+
return typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,120}$/.test(value) ? value : undefined;
|
|
53
|
+
}
|
|
54
|
+
// Codewhale v0.9.12 parse_agent_tool_action; aliases are native protocol, not UI guesses.
|
|
55
|
+
export const CODEWHALE_OPERATIONS = {
|
|
56
|
+
'': 'start', start: 'start', spawn: 'start', run: 'start',
|
|
57
|
+
roster: 'roster', members: 'roster', profiles: 'roster',
|
|
58
|
+
status: 'status', list: 'status', inspect: 'status', peek: 'peek', progress: 'peek',
|
|
59
|
+
message: 'message', queue_message: 'message', followup: 'followup', follow_up: 'followup', steer: 'followup',
|
|
60
|
+
interrupt: 'interrupt', pause: 'interrupt', wait: 'wait', join: 'wait', await: 'wait', block: 'wait',
|
|
61
|
+
cancel: 'cancel', stop: 'cancel', abort: 'cancel', claim: 'claim',
|
|
62
|
+
};
|
|
63
|
+
export const CODEWHALE_STATES = {
|
|
64
|
+
queued: 'queued', starting: 'running', running: 'running', model_wait: 'waiting',
|
|
65
|
+
waiting_for_user: 'waiting', running_tool: 'running', completed: 'completed', failed: 'failed',
|
|
66
|
+
cancelled: 'cancelled', interrupted: 'paused', interrupted_continuable: 'paused', budget_exhausted: 'failed',
|
|
67
|
+
};
|
|
68
|
+
function target(id, status) {
|
|
69
|
+
const key = typeof status === 'string' ? status : '';
|
|
70
|
+
return { id, state: Object.hasOwn(CODEWHALE_STATES, key) ? CODEWHALE_STATES[key] : 'unknown',
|
|
71
|
+
...(status === 'model_wait' ? { wait_reason: 'model' }
|
|
72
|
+
: status === 'waiting_for_user' ? { wait_reason: 'user' } : {}) };
|
|
73
|
+
}
|
|
74
|
+
/** Per-turn correlation lives at the native adapter boundary. Never match concurrent calls by name. */
|
|
75
|
+
export class ToolSemantics {
|
|
76
|
+
supportsAgentActions;
|
|
77
|
+
calls = new Map();
|
|
78
|
+
constructor(supportsAgentActions) {
|
|
79
|
+
this.supportsAgentActions = supportsAgentActions;
|
|
80
|
+
}
|
|
81
|
+
normalize(block) {
|
|
82
|
+
if (block.kind !== 'tool_use' && block.kind !== 'tool_result')
|
|
83
|
+
return block;
|
|
84
|
+
const callId = toolCallId(block.raw);
|
|
85
|
+
const previous = callId ? this.calls.get(callId) : undefined;
|
|
86
|
+
const name = (typeof block.name === 'string' ? block.name : previous?.name ?? '').toLowerCase();
|
|
87
|
+
const input = object(field(block.raw, ['input', 'arguments', 'args']));
|
|
88
|
+
let result = object(field(block.raw, ['output', 'result']));
|
|
89
|
+
// Native tool results may use a text content envelope containing JSON.
|
|
90
|
+
if (Array.isArray(result.content)) {
|
|
91
|
+
const text = result.content.map(object).find(x => x.type === 'text' && typeof x.text === 'string');
|
|
92
|
+
if (text)
|
|
93
|
+
result = object(text.text);
|
|
94
|
+
}
|
|
95
|
+
const nativeAction = input.action ?? input.op ?? result.action
|
|
96
|
+
?? (block.kind === 'tool_use' ? 'start' : undefined);
|
|
97
|
+
const action = typeof nativeAction === 'string' ? nativeAction.trim().toLowerCase() : undefined;
|
|
98
|
+
const operation = this.supportsAgentActions && name === 'agent' && action !== undefined
|
|
99
|
+
&& Object.hasOwn(CODEWHALE_OPERATIONS, action) ? CODEWHALE_OPERATIONS[action] : undefined;
|
|
100
|
+
const activity = {
|
|
101
|
+
schema_version: 'runtime-activity/1', kind: operation ? 'subtask' : 'tool',
|
|
102
|
+
operation: operation ?? toolAction(name), ...(callId ? { call_id: callId } : {}),
|
|
103
|
+
targets: [], ...(previous?.activity ?? {}),
|
|
104
|
+
outcome: block.kind === 'tool_use' ? 'pending' : block.status === 'error' ? 'failed'
|
|
105
|
+
: result.timed_out === true ? 'timed_out' : block.status === 'completed' ? 'success' : 'unknown',
|
|
106
|
+
};
|
|
107
|
+
if (activity.kind === 'subtask') {
|
|
108
|
+
const ids = [input.agent_id ?? input.id, ...(Array.isArray(input.agent_ids) ? input.agent_ids : [])]
|
|
109
|
+
.map(safeId).filter((id) => Boolean(id));
|
|
110
|
+
if (ids.length)
|
|
111
|
+
activity.targets = ids.map(id => target(id, undefined));
|
|
112
|
+
const ownId = safeId(result.agent_id);
|
|
113
|
+
const candidates = [...(ownId ? [result] : []),
|
|
114
|
+
...(Array.isArray(result.agents) ? result.agents.map(object) : []),
|
|
115
|
+
...(Array.isArray(result.settled) ? result.settled.map(object) : [])];
|
|
116
|
+
const targets = new Map(activity.targets.map(t => [t.id, t]));
|
|
117
|
+
for (const item of candidates) {
|
|
118
|
+
const id = safeId(item.agent_id);
|
|
119
|
+
if (id)
|
|
120
|
+
targets.set(id, target(id, item.status));
|
|
121
|
+
}
|
|
122
|
+
activity.targets = [...targets.values()];
|
|
123
|
+
if (result.timed_out === true)
|
|
124
|
+
activity.targets = activity.targets.map(t => t.state === 'unknown' ? { ...t, state: 'running' } : t);
|
|
125
|
+
}
|
|
126
|
+
if (callId) {
|
|
127
|
+
if (block.kind === 'tool_use')
|
|
128
|
+
this.calls.set(callId, { name, activity });
|
|
129
|
+
else if (activity.outcome !== 'unknown')
|
|
130
|
+
this.calls.delete(callId);
|
|
131
|
+
}
|
|
132
|
+
return { ...block, name: block.name ?? previous?.name, activity };
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { RuntimeBlock } from "./types.js";
|
|
2
|
-
export declare const AGENT_TOOL_OBSERVATION_SCHEMA_VERSION = "agent-tool-observation/0.
|
|
2
|
+
export declare const AGENT_TOOL_OBSERVATION_SCHEMA_VERSION = "agent-tool-observation/0.2";
|
|
3
3
|
export interface ToolObservationPayload extends Record<string, unknown> {
|
|
4
4
|
schema_version: typeof AGENT_TOOL_OBSERVATION_SCHEMA_VERSION;
|
|
5
5
|
kind: "tool_call" | "tool_result";
|
|
@@ -24,3 +24,4 @@ export interface ToolObservationPayload extends Record<string, unknown> {
|
|
|
24
24
|
* arbitrary envelope metadata never cross this boundary.
|
|
25
25
|
*/
|
|
26
26
|
export declare function buildToolObservation(block: RuntimeBlock, runtime: string, workspaceDir: string): ToolObservationPayload | null;
|
|
27
|
+
export declare function toolCallId(raw: unknown, depth?: number): string | undefined;
|
package/dist/tool-observation.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
2
|
import { REDACTED, redactSecretsDeep, } from "./redaction.js";
|
|
3
|
-
export const AGENT_TOOL_OBSERVATION_SCHEMA_VERSION = "agent-tool-observation/0.
|
|
3
|
+
export const AGENT_TOOL_OBSERVATION_SCHEMA_VERSION = "agent-tool-observation/0.2";
|
|
4
4
|
const DETAIL_MAX_CHARS = 4_000;
|
|
5
5
|
const DETAIL_FULL_MAX_CHARS = 64_000;
|
|
6
6
|
const MAX_PROJECT_DEPTH = 8;
|
|
@@ -81,6 +81,8 @@ export function buildToolObservation(block, runtime, workspaceDir) {
|
|
|
81
81
|
return {
|
|
82
82
|
...(callId ? { tool_call_id: callId } : {}),
|
|
83
83
|
schema_version: AGENT_TOOL_OBSERVATION_SCHEMA_VERSION,
|
|
84
|
+
activity: block.activity ?? { schema_version: "runtime-activity/1", kind: "tool",
|
|
85
|
+
operation: "operate", outcome: block.kind === "tool_call" ? "pending" : block.status === "error" ? "failed" : "success", targets: [] },
|
|
84
86
|
kind: block.kind,
|
|
85
87
|
runtime,
|
|
86
88
|
status: block.kind === "tool_call"
|
|
@@ -145,7 +147,7 @@ function normalizeWorkspacePaths(value, workspaceDir) {
|
|
|
145
147
|
normalizeWorkspacePaths(item, workspaceDir),
|
|
146
148
|
]));
|
|
147
149
|
}
|
|
148
|
-
function toolCallId(raw, depth = 0) {
|
|
150
|
+
export function toolCallId(raw, depth = 0) {
|
|
149
151
|
if (!raw || typeof raw !== "object" || depth > 4)
|
|
150
152
|
return undefined;
|
|
151
153
|
const value = raw;
|
package/dist/types.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { RuntimeActivity, RuntimeMetadata } from "./runtime-activity.js";
|
|
1
2
|
import type { RuntimePrompt } from "./runtime-prompt.js";
|
|
2
3
|
/**
|
|
3
4
|
* Course-native 协议与 runtime 契约(spec: docs/specs/lightweight-course-daemon-package.md)。
|
|
@@ -139,6 +140,7 @@ export interface AppliedRunRuntimeProfile {
|
|
|
139
140
|
}
|
|
140
141
|
/** runtime adapter 产出的普通归一化块;raw 仅进本地 transcript。 */
|
|
141
142
|
export interface RuntimeContentBlock {
|
|
143
|
+
activity?: RuntimeActivity;
|
|
142
144
|
kind: "text_delta" | "text" | "thinking" | "tool_call" | "tool_result" | "status" | "error";
|
|
143
145
|
text?: string;
|
|
144
146
|
/**
|
|
@@ -204,6 +206,7 @@ export interface RuntimeProbe {
|
|
|
204
206
|
}
|
|
205
207
|
/** runtime 执行期间向 dispatcher 汇报的通道。adapter 不直接触碰 Course API。 */
|
|
206
208
|
export interface CourseRuntimeSink {
|
|
209
|
+
runtimeMetadata?(metadata: RuntimeMetadata): Promise<void>;
|
|
207
210
|
block(block: RuntimeBlock): Promise<void>;
|
|
208
211
|
message(text: string): Promise<void>;
|
|
209
212
|
file(file: RunFileCandidate): Promise<void>;
|
package/package.json
CHANGED