@causyne/agent 1.20.12 → 1.20.14
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/LICENSE +1 -1
- package/package.json +1 -1
- package/src/SmartTools.js +33 -0
- package/src/SmartTools.ts +37 -0
- package/src/acp/client.js +157 -4
- package/src/acp/client.ts +152 -5
- package/src/agentLoop.js +857 -178
- package/src/agentLoop.ts +865 -183
- package/src/browser/browserRuntime.js +8 -1
- package/src/browser/browserRuntime.ts +8 -1
- package/src/browser/causyneBrowser.js +20 -4
- package/src/browser/causyneBrowser.ts +20 -4
- package/src/browser/urlPolicy.js +35 -0
- package/src/browser/urlPolicy.ts +34 -0
- package/src/cliMode.js +6 -2
- package/src/commands.js +14 -0
- package/src/contextManager.d.ts +1 -0
- package/src/core/contextCompactor.js +277 -0
- package/src/core/contextCompactor.ts +353 -0
- package/src/decideTools.js +157 -0
- package/src/decideTools.ts +195 -0
- package/src/decisionPolicy.js +5 -3
- package/src/decisionPolicy.ts +5 -3
- package/src/implementationPlan.js +284 -0
- package/src/implementationPlan.ts +275 -0
- package/src/observer/coldObserver.js +10 -4
- package/src/observer/coldObserver.ts +15 -7
- package/src/observer/evidence.js +11 -5
- package/src/observer/evidence.ts +13 -6
- package/src/observer.js +196 -0
- package/src/observer.ts +287 -0
- package/src/providers/acp.js +362 -109
- package/src/providers/acp.ts +359 -111
- package/src/providers/antigravity.js +133 -105
- package/src/providers/antigravity.ts +130 -109
- package/src/providers/base.d.ts +3 -0
- package/src/providers/budgetEnforcer.js +13 -0
- package/src/providers/budgetEnforcer.ts +13 -3
- package/src/provisioning/capabilityProvisioner.js +14 -10
- package/src/sandbox.js +4 -2
- package/src/saveTools.js +146 -0
- package/src/saveTools.ts +169 -0
- package/src/session/cachePressure.js +77 -0
- package/src/session/cachePressure.ts +122 -0
- package/src/smartToolsUse.js +69 -12
- package/src/smartToolsUse.ts +103 -12
- package/src/taskShape.js +7 -7
- package/src/taskShape.ts +7 -7
- package/src/timeMachine.js +55 -20
- package/src/timeMachine.ts +64 -20
- package/src/toolPacks.js +217 -310
- package/src/toolPacks.ts +505 -0
- package/src/tools/deferredMcpSearch.js +21 -13
- package/src/tools/deferredMcpSearch.ts +23 -15
- package/src/tools/updatePlan.js +2 -2
- package/src/tools/updatePlan.ts +2 -2
- package/src/toolsList.js +203 -0
- package/src/toolsList.ts +224 -0
- package/src/tui/chatRenderer.js +49 -14
- package/src/tui/codeStreamRenderer.js +16 -5
- package/src/tui/codeStreamRenderer.ts +14 -4
- package/src/tui/prompt.js +4 -2
- package/src/tui/sessionSidebar.js +10 -2
- package/src/tui/sessionSidebar.ts +10 -3
- package/src/tui/stageSurface.js +27 -1
- package/src/tui/text.d.ts +1 -0
- package/src/tui/turnRail.js +274 -0
- package/src/tui/turnRail.ts +334 -0
- package/src/types/contracts.ts +103 -0
- package/src/verificationPlan.js +141 -0
- package/src/verificationPlan.ts +166 -0
- package/src/toolPacks.d.ts +0 -10
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/decideTools.ts
|
|
3
|
+
* decideTools — stage 2 of the tool pipeline.
|
|
4
|
+
*
|
|
5
|
+
* user intent -> ToolsList -> decideTools -> SmartTools -> saveTools -> AgentLoop
|
|
6
|
+
*
|
|
7
|
+
* Decides WHICH listed tools a task needs. It never loads anything and never
|
|
8
|
+
* runs a model: it is a pure function over the intent, the task shape and the
|
|
9
|
+
* ToolsList, so it costs no tokens and is identical on every provider.
|
|
10
|
+
*
|
|
11
|
+
* It is entered again whenever the work changes shape — the model asks for a
|
|
12
|
+
* tool, an implementation plan is accepted, verification needs evidence, or a
|
|
13
|
+
* failure demands a different route — and always from the same list.
|
|
14
|
+
*
|
|
15
|
+
* Authorship: Strict TypeScript (Causyne Agent).
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { determineToolScope, filterSuppressedPacks } from './smartToolsUse.js';
|
|
19
|
+
import { routePacks, packForTool, PACK_NAMES } from './toolPacks.js';
|
|
20
|
+
import type { PackName, WorkspaceRoutingContext } from './toolPacks.js';
|
|
21
|
+
import { packsFromShape } from './taskShape.js';
|
|
22
|
+
import type { TaskShape } from './types/contracts.js';
|
|
23
|
+
import type { ToolListEntry } from './toolsList.js';
|
|
24
|
+
import { buildToolsList } from './toolsList.js';
|
|
25
|
+
|
|
26
|
+
export type DecisionSource = 'intent' | 'request' | 'plan' | 'verification' | 'recovery';
|
|
27
|
+
|
|
28
|
+
export interface DecideToolsInput {
|
|
29
|
+
readonly source: DecisionSource;
|
|
30
|
+
readonly list: readonly ToolListEntry[];
|
|
31
|
+
/** The user's order. Required for `intent`. */
|
|
32
|
+
readonly prompt?: string;
|
|
33
|
+
readonly taskShape?: TaskShape | null;
|
|
34
|
+
readonly workspace?: WorkspaceRoutingContext | null;
|
|
35
|
+
/**
|
|
36
|
+
* Tool names the model asked for, by calling or searching. The caller has
|
|
37
|
+
* already resolved them against the live registry, so a plugin or MCP tool
|
|
38
|
+
* beyond the list's bounded custom section is still honoured.
|
|
39
|
+
*/
|
|
40
|
+
readonly requested?: readonly string[];
|
|
41
|
+
/** Whole packs the model asked for with `tool_search`. */
|
|
42
|
+
readonly requestedPacks?: readonly string[];
|
|
43
|
+
/** Plan step text, a verification need, or a failure summary to scan for needs. */
|
|
44
|
+
readonly text?: string;
|
|
45
|
+
/** A previously successful route for a similar task. */
|
|
46
|
+
readonly cachedTools?: readonly string[];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface ToolDecision {
|
|
50
|
+
readonly source: DecisionSource;
|
|
51
|
+
/** Individual tools to admit. */
|
|
52
|
+
readonly tools: string[];
|
|
53
|
+
/** Whole packs to admit; only `intent` ever asks for a pack. */
|
|
54
|
+
readonly packs: PackName[];
|
|
55
|
+
readonly archetype: string;
|
|
56
|
+
readonly suppressedPacks: readonly string[];
|
|
57
|
+
readonly reasons: string[];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A single decision from free text never admits more than this many tools. */
|
|
61
|
+
export const MAX_TEXT_TOOLS = 8;
|
|
62
|
+
|
|
63
|
+
/** A Three.js, WebGL, canvas or Python game needs no engine pack. */
|
|
64
|
+
export function isDirectGameTask(text: string): boolean {
|
|
65
|
+
return /\b(three?\.?js|3js|webgl|canvas|html5|pygame)\b/i.test(text)
|
|
66
|
+
&& !/\b(godot|unity|unreal|full engine)\b/i.test(text);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
interface Trigger {
|
|
70
|
+
readonly pattern: RegExp;
|
|
71
|
+
readonly tools: readonly string[];
|
|
72
|
+
readonly why: string;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* What a plan step, a verification need or a failure implies. Every name here
|
|
77
|
+
* is checked against the ToolsList before use, so a stale entry is inert.
|
|
78
|
+
*/
|
|
79
|
+
const TRIGGERS: readonly Trigger[] = [
|
|
80
|
+
{ pattern: /\b(preview|screenshot|visual(?:ly)?|rendered? (?:page|output|ui)|browser|snapshot|look at (?:the )?(?:ui|page|screen))\b/i,
|
|
81
|
+
tools: ['browser_act', 'screenshot', 'view_image'], why: 'rendered output must be looked at' },
|
|
82
|
+
{ pattern: /\b(vision|ocr|inspect (?:the )?(?:ui|screen))\b/i, tools: ['vision_inspect_ui'], why: 'screen inspection' },
|
|
83
|
+
{ pattern: /\b(blender(?:_act)?|3d\b|mesh|render (?:frame|animation|model)?)\b/i, tools: ['blender_act', 'view_image'], why: '3D work' },
|
|
84
|
+
{ pattern: /\b(pdf|docx?|document|proposal|screenplay|shot ?list|report)\b/i, tools: ['document_forge', 'pdf_read'], why: 'document production' },
|
|
85
|
+
{ pattern: /\b(image|illustration|logo|poster|thumbnail|music|song|voice|tts|narration|video)\b/i,
|
|
86
|
+
tools: ['generate_media_via_api', 'execute_procedural_media'], why: 'media generation' },
|
|
87
|
+
{ pattern: /\b(kill|terminate|port \d+|processes?)\b/i, tools: ['process_list', 'proc_term'], why: 'process control' },
|
|
88
|
+
{ pattern: /\b(zip|unzip|archive|extract|tarball)\b/i, tools: ['archive'], why: 'archive handling' },
|
|
89
|
+
{ pattern: /\b(sub-?agents?|in parallel|delegate)\b/i, tools: ['agent_subagent_orchestrate'], why: 'delegation' },
|
|
90
|
+
{ pattern: /\b(symbols?|definitions?|ast)\b/i, tools: ['code_list_symbols', 'code_search_ast'], why: 'structural code search' },
|
|
91
|
+
{ pattern: /\b(syntax|compile|typecheck|lint)\b/i, tools: ['code_verify_syntax'], why: 'static check' },
|
|
92
|
+
{ pattern: /\b(godot|\.tscn|gdscript)\b/i, tools: ['godot_act', 'game_scene_build'], why: 'Godot work' },
|
|
93
|
+
{ pattern: /\b(clipboard)\b/i, tools: ['clipboard'], why: 'clipboard' },
|
|
94
|
+
{ pattern: /\b(gui|desktop app|accessibility|click (?:the )?button)\b/i, tools: ['ax_snapshot', 'desktop_act'], why: 'GUI control' },
|
|
95
|
+
{ pattern: /\b(commit|branch|merge|rebase)\b/i, tools: ['gitOp'], why: 'version control' },
|
|
96
|
+
{ pattern: /\b(search the web|look up|latest version|official docs?|documentation)\b/i, tools: ['web_search', 'web_fetch'], why: 'external facts' },
|
|
97
|
+
{ pattern: /\b(ask the user|decide between|which (?:option|approach))\b/i, tools: ['request_decision'], why: 'user decision' },
|
|
98
|
+
{ pattern: /\b(hardware|gpu|disk space|ram)\b/i, tools: ['check_system_specs'], why: 'hardware check' }
|
|
99
|
+
];
|
|
100
|
+
|
|
101
|
+
function listed(list?: readonly ToolListEntry[]): Map<string, string> {
|
|
102
|
+
const entries = Array.isArray(list) ? list : buildToolsList();
|
|
103
|
+
const byLower = new Map<string, string>();
|
|
104
|
+
for (const entry of entries) byLower.set(entry.name.toLowerCase(), entry.name);
|
|
105
|
+
return byLower;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function unique(values: Iterable<string>): string[] {
|
|
109
|
+
return [...new Set(values)];
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Match free text against the triggers, restricted to tools that are actually listed. */
|
|
113
|
+
export function toolsForText(text: string, list?: readonly ToolListEntry[]): { tools: string[]; reasons: string[] } {
|
|
114
|
+
const known = listed(list);
|
|
115
|
+
const tools: string[] = [];
|
|
116
|
+
const reasons: string[] = [];
|
|
117
|
+
for (const trigger of TRIGGERS) {
|
|
118
|
+
if (!trigger.pattern.test(text)) continue;
|
|
119
|
+
const present = trigger.tools.filter((name) => known.has(name.toLowerCase()));
|
|
120
|
+
if (present.length === 0) continue;
|
|
121
|
+
for (const name of present) if (!tools.includes(name)) tools.push(name);
|
|
122
|
+
reasons.push(trigger.why);
|
|
123
|
+
if (tools.length >= MAX_TEXT_TOOLS) break;
|
|
124
|
+
}
|
|
125
|
+
return { tools: tools.slice(0, MAX_TEXT_TOOLS), reasons };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function decideTools(input: DecideToolsInput): ToolDecision {
|
|
129
|
+
const known = listed(input.list);
|
|
130
|
+
const reasons: string[] = [];
|
|
131
|
+
const tools: string[] = [];
|
|
132
|
+
const packs: PackName[] = [];
|
|
133
|
+
let archetype = 'generalist';
|
|
134
|
+
let suppressedPacks: readonly string[] = [];
|
|
135
|
+
|
|
136
|
+
// Names the model asked for are honoured; a listed name is canonicalised.
|
|
137
|
+
for (const raw of input.requested ?? []) {
|
|
138
|
+
const name = String(raw ?? '').trim();
|
|
139
|
+
if (!name) continue;
|
|
140
|
+
const canonical = known.get(name.toLowerCase());
|
|
141
|
+
if (canonical) tools.push(canonical);
|
|
142
|
+
}
|
|
143
|
+
if (tools.length > 0) reasons.push(`requested: ${tools.join(', ')}`);
|
|
144
|
+
|
|
145
|
+
const validPacks = new Set<string>(PACK_NAMES);
|
|
146
|
+
for (const pack of input.requestedPacks ?? []) {
|
|
147
|
+
if (validPacks.has(pack)) packs.push(pack as PackName);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const effectiveSource = input.source ?? (input.prompt ? 'intent' : 'request');
|
|
151
|
+
if (effectiveSource === 'intent') {
|
|
152
|
+
const prompt = input.prompt ?? '';
|
|
153
|
+
const scope = determineToolScope(prompt, input.taskShape);
|
|
154
|
+
archetype = scope.archetype;
|
|
155
|
+
suppressedPacks = scope.suppressedPacks;
|
|
156
|
+
if (scope.toolScope) {
|
|
157
|
+
for (const name of scope.toolScope) {
|
|
158
|
+
const canonical = known.get(name.toLowerCase());
|
|
159
|
+
if (canonical) tools.push(canonical);
|
|
160
|
+
}
|
|
161
|
+
reasons.push(`scope ${scope.archetype}`);
|
|
162
|
+
}
|
|
163
|
+
const scored = packsFromShape(input.taskShape ?? null);
|
|
164
|
+
const fallback = routePacks(prompt, input.workspace ?? null);
|
|
165
|
+
const candidates = filterSuppressedPacks([...scored, ...fallback], prompt);
|
|
166
|
+
for (const pack of candidates) {
|
|
167
|
+
if (!validPacks.has(pack)) continue;
|
|
168
|
+
if (pack === 'game' && isDirectGameTask(prompt)) continue;
|
|
169
|
+
packs.push(pack as PackName);
|
|
170
|
+
}
|
|
171
|
+
if (packs.length > 0) reasons.push(`suggested domains ${packs.join(', ')}`);
|
|
172
|
+
for (const name of input.cachedTools ?? []) {
|
|
173
|
+
const canonical = known.get(name.toLowerCase());
|
|
174
|
+
if (!canonical) continue;
|
|
175
|
+
tools.push(canonical);
|
|
176
|
+
// A cached route admits IDs only, never an entire domain or permissions.
|
|
177
|
+
}
|
|
178
|
+
if ((input.cachedTools?.length ?? 0) > 0) reasons.push('proven route');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (input.text) {
|
|
182
|
+
const found = toolsForText(input.text, input.list);
|
|
183
|
+
for (const name of found.tools) tools.push(name);
|
|
184
|
+
for (const why of found.reasons) reasons.push(why);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return {
|
|
188
|
+
source: input.source,
|
|
189
|
+
tools: unique(tools),
|
|
190
|
+
packs: unique(packs) as PackName[],
|
|
191
|
+
archetype,
|
|
192
|
+
suppressedPacks,
|
|
193
|
+
reasons
|
|
194
|
+
};
|
|
195
|
+
}
|
package/src/decisionPolicy.js
CHANGED
|
@@ -16,7 +16,9 @@ const EXPLICIT_CHOICE_PATTERNS = [
|
|
|
16
16
|
];
|
|
17
17
|
const MUTATING_TOOLS = new Set([
|
|
18
18
|
'fs_write', 'fs_edit', 'MultiEdit', 'fs_delete', 'fs_move', 'sysRun', 'sysRunBg',
|
|
19
|
-
'gitOp', 'manage_local_dependencies', 'plugin_manage', 'tool_forge', 'create_skill'
|
|
19
|
+
'gitOp', 'manage_local_dependencies', 'plugin_manage', 'tool_forge', 'create_skill',
|
|
20
|
+
'write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content',
|
|
21
|
+
'write', 'edit', 'multiedit', 'bash', 'terminal', 'execute'
|
|
20
22
|
]);
|
|
21
23
|
function containsAny(text, terms) {
|
|
22
24
|
return terms.some(term => text.includes(term));
|
|
@@ -63,8 +65,8 @@ export function isMutatingToolCall(toolName, args = {}) {
|
|
|
63
65
|
if (toolName === 'native_engine')
|
|
64
66
|
return !['status', 'catalog', 'describe', 'inspect', 'probe'].includes(String(args.action ?? ''));
|
|
65
67
|
if (MUTATING_TOOLS.has(toolName)) {
|
|
66
|
-
if (
|
|
67
|
-
const command = String(args.command ?? '');
|
|
68
|
+
if (['sysRun', 'sysRunBg', 'bash', 'terminal', 'execute', 'sh', 'zsh'].includes(toolName)) {
|
|
69
|
+
const command = String(args.command ?? args.cmd ?? '');
|
|
68
70
|
return !/^\s*(?:pwd|ls|find|rg|grep|cat|sed|head|tail|git\s+(?:status|diff|log|show)|npm\s+(?:view|audit|test)|node\s+--check)\b/i.test(command);
|
|
69
71
|
}
|
|
70
72
|
if (toolName === 'gitOp') {
|
package/src/decisionPolicy.ts
CHANGED
|
@@ -50,7 +50,9 @@ const EXPLICIT_CHOICE_PATTERNS = [
|
|
|
50
50
|
|
|
51
51
|
const MUTATING_TOOLS = new Set([
|
|
52
52
|
'fs_write', 'fs_edit', 'MultiEdit', 'fs_delete', 'fs_move', 'sysRun', 'sysRunBg',
|
|
53
|
-
'gitOp', 'manage_local_dependencies', 'plugin_manage', 'tool_forge', 'create_skill'
|
|
53
|
+
'gitOp', 'manage_local_dependencies', 'plugin_manage', 'tool_forge', 'create_skill',
|
|
54
|
+
'write_file', 'write_to_file', 'edit_file', 'replace_file_content', 'multi_replace_file_content',
|
|
55
|
+
'write', 'edit', 'multiedit', 'bash', 'terminal', 'execute'
|
|
54
56
|
]);
|
|
55
57
|
|
|
56
58
|
function containsAny(text: string, terms: readonly string[]): boolean {
|
|
@@ -99,8 +101,8 @@ export function isMutatingToolCall(toolName: string, args: Record<string, unknow
|
|
|
99
101
|
if (toolName === 'creative_apps') return args.action !== 'status';
|
|
100
102
|
if (toolName === 'native_engine') return !['status', 'catalog', 'describe', 'inspect', 'probe'].includes(String(args.action ?? ''));
|
|
101
103
|
if (MUTATING_TOOLS.has(toolName)) {
|
|
102
|
-
if (
|
|
103
|
-
const command = String(args.command ?? '');
|
|
104
|
+
if (['sysRun', 'sysRunBg', 'bash', 'terminal', 'execute', 'sh', 'zsh'].includes(toolName)) {
|
|
105
|
+
const command = String(args.command ?? args.cmd ?? '');
|
|
104
106
|
return !/^\s*(?:pwd|ls|find|rg|grep|cat|sed|head|tail|git\s+(?:status|diff|log|show)|npm\s+(?:view|audit|test)|node\s+--check)\b/i.test(command);
|
|
105
107
|
}
|
|
106
108
|
if (toolName === 'gitOp') {
|
|
@@ -48,3 +48,287 @@ export function summarizePlan(plan) {
|
|
|
48
48
|
const active = plan.find(item => item.status === 'in_progress');
|
|
49
49
|
return `${completed}/${plan.length} completed${active ? `; in progress: ${active.step}` : ''}`;
|
|
50
50
|
}
|
|
51
|
+
export function normalizePeerPlanEntries(value) {
|
|
52
|
+
if (!value)
|
|
53
|
+
return null;
|
|
54
|
+
let rawList = null;
|
|
55
|
+
let explanation = '';
|
|
56
|
+
if (Array.isArray(value)) {
|
|
57
|
+
rawList = value;
|
|
58
|
+
}
|
|
59
|
+
else if (typeof value === 'object') {
|
|
60
|
+
const obj = value;
|
|
61
|
+
if (typeof obj.explanation === 'string') {
|
|
62
|
+
explanation = obj.explanation.replace(/\s+/g, ' ').trim().slice(0, 500);
|
|
63
|
+
}
|
|
64
|
+
const candidate = obj.plan ?? obj.todos ?? obj.entries ?? obj.steps ?? obj.items ?? obj.tasks
|
|
65
|
+
?? (obj.metadata && typeof obj.metadata === 'object' ? obj.metadata.todos : undefined);
|
|
66
|
+
if (Array.isArray(candidate)) {
|
|
67
|
+
rawList = candidate;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (!rawList || rawList.length === 0)
|
|
71
|
+
return null;
|
|
72
|
+
const ids = new Set();
|
|
73
|
+
let activeSeen = false;
|
|
74
|
+
const steps = [];
|
|
75
|
+
for (let i = 0; i < Math.min(rawList.length, MAX_STEPS); i++) {
|
|
76
|
+
const raw = rawList[i];
|
|
77
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
78
|
+
continue;
|
|
79
|
+
const item = raw;
|
|
80
|
+
const rawText = item.step ?? item.content ?? item.text ?? item.title ?? item.name ?? item.description;
|
|
81
|
+
if (typeof rawText !== 'string')
|
|
82
|
+
continue;
|
|
83
|
+
const step = rawText.replace(/\s+/g, ' ').trim().slice(0, 240);
|
|
84
|
+
if (!step)
|
|
85
|
+
continue;
|
|
86
|
+
const baseId = typeof item.id === 'string' && item.id.trim()
|
|
87
|
+
? item.id.replace(/\s+/g, ' ').trim().slice(0, 56)
|
|
88
|
+
: `step-${steps.length + 1}`;
|
|
89
|
+
let id = baseId;
|
|
90
|
+
let suffix = 2;
|
|
91
|
+
while (ids.has(id)) {
|
|
92
|
+
id = `${baseId}-${suffix++}`;
|
|
93
|
+
}
|
|
94
|
+
ids.add(id);
|
|
95
|
+
const rawStatus = String(item.status ?? item.state ?? 'pending').toLowerCase().trim();
|
|
96
|
+
let status = 'pending';
|
|
97
|
+
if (rawStatus === 'completed' || rawStatus === 'done' || rawStatus === 'complete' || rawStatus === 'finished') {
|
|
98
|
+
status = 'completed';
|
|
99
|
+
}
|
|
100
|
+
else if (rawStatus === 'in_progress' || rawStatus === 'in-progress' || rawStatus === 'in progress' || rawStatus === 'active' || rawStatus === 'running' || rawStatus === 'working') {
|
|
101
|
+
status = 'in_progress';
|
|
102
|
+
}
|
|
103
|
+
if (status === 'in_progress') {
|
|
104
|
+
if (activeSeen) {
|
|
105
|
+
status = 'pending';
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
activeSeen = true;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
steps.push({ id, step, status });
|
|
112
|
+
}
|
|
113
|
+
if (steps.length === 0)
|
|
114
|
+
return null;
|
|
115
|
+
if (!activeSeen && steps.some(s => s.status === 'pending')) {
|
|
116
|
+
const firstPending = steps.find(s => s.status === 'pending');
|
|
117
|
+
if (firstPending)
|
|
118
|
+
firstPending.status = 'in_progress';
|
|
119
|
+
}
|
|
120
|
+
return { explanation, plan: steps };
|
|
121
|
+
}
|
|
122
|
+
export function extractToolCallJsonObjects(text) {
|
|
123
|
+
const results = [];
|
|
124
|
+
if (!text || typeof text !== 'string')
|
|
125
|
+
return results;
|
|
126
|
+
const tagRegex = /<tool_call>/gi;
|
|
127
|
+
let tagMatch;
|
|
128
|
+
while ((tagMatch = tagRegex.exec(text)) !== null) {
|
|
129
|
+
const startSearch = tagMatch.index + tagMatch[0].length;
|
|
130
|
+
const braceStart = text.indexOf('{', startSearch);
|
|
131
|
+
if (braceStart === -1)
|
|
132
|
+
continue;
|
|
133
|
+
// Ensure only whitespace separates <tool_call> and '{'
|
|
134
|
+
if (text.slice(startSearch, braceStart).trim().length > 0)
|
|
135
|
+
continue;
|
|
136
|
+
let depth = 0;
|
|
137
|
+
let inString = false;
|
|
138
|
+
let escaped = false;
|
|
139
|
+
let endBrace = -1;
|
|
140
|
+
for (let i = braceStart; i < text.length; i++) {
|
|
141
|
+
const ch = text[i];
|
|
142
|
+
if (inString) {
|
|
143
|
+
if (escaped) {
|
|
144
|
+
escaped = false;
|
|
145
|
+
}
|
|
146
|
+
else if (ch === '\\') {
|
|
147
|
+
escaped = true;
|
|
148
|
+
}
|
|
149
|
+
else if (ch === '"') {
|
|
150
|
+
inString = false;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
if (ch === '"') {
|
|
155
|
+
inString = true;
|
|
156
|
+
}
|
|
157
|
+
else if (ch === '{') {
|
|
158
|
+
depth++;
|
|
159
|
+
}
|
|
160
|
+
else if (ch === '}') {
|
|
161
|
+
depth--;
|
|
162
|
+
if (depth === 0) {
|
|
163
|
+
endBrace = i;
|
|
164
|
+
break;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (endBrace !== -1) {
|
|
170
|
+
const candidate = text.slice(braceStart, endBrace + 1);
|
|
171
|
+
try {
|
|
172
|
+
const parsed = JSON.parse(candidate);
|
|
173
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
174
|
+
results.push(parsed);
|
|
175
|
+
tagRegex.lastIndex = endBrace + 1;
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
// Fall through to suffix healing below
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
// Unclosed or truncated JSON after <tool_call>: strip trailing XML/DSML closing tags and heal
|
|
184
|
+
const nextTagIndex = text.indexOf('<tool_call>', braceStart + 1);
|
|
185
|
+
const sliceEnd = nextTagIndex === -1 ? text.length : nextTagIndex;
|
|
186
|
+
const rawSlice = text
|
|
187
|
+
.slice(braceStart, sliceEnd)
|
|
188
|
+
.replace(/(?:\s*<\/?(?:tool_call|[||]DSML[||][^>]*|invoke|parameter|calls|function_calls)>)+[\s\S]*$/i, '')
|
|
189
|
+
.trim();
|
|
190
|
+
for (const suffix of ['', '}', '}}', '}}}', '"}', '"}}', '"}}}', '"}]}}', '"]}}', '"]}}}']) {
|
|
191
|
+
try {
|
|
192
|
+
const parsed = JSON.parse(rawSlice + suffix);
|
|
193
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
194
|
+
results.push(parsed);
|
|
195
|
+
break;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
// try next suffix
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (results.length === 0) {
|
|
204
|
+
const dsmlInvokeRegex = /<[||]DSML[||]\s*invoke\s+name="([^"]+)"[^>]*>([\s\S]*?)<\/[||]DSML[||]\s*invoke>/gi;
|
|
205
|
+
let invokeMatch;
|
|
206
|
+
while ((invokeMatch = dsmlInvokeRegex.exec(text)) !== null) {
|
|
207
|
+
const name = (invokeMatch[1] || '').trim();
|
|
208
|
+
const body = invokeMatch[2] || '';
|
|
209
|
+
if (!name)
|
|
210
|
+
continue;
|
|
211
|
+
const args = {};
|
|
212
|
+
const paramRegex = /<[||]DSML[||]\s*parameter\s+name="([^"]+)"[^>]*>([\s\S]*?)<\/[||]DSML[||]\s*parameter>/gi;
|
|
213
|
+
let paramMatch;
|
|
214
|
+
while ((paramMatch = paramRegex.exec(body)) !== null) {
|
|
215
|
+
const key = (paramMatch[1] || '').trim();
|
|
216
|
+
const valRaw = (paramMatch[2] || '').trim();
|
|
217
|
+
if (!key)
|
|
218
|
+
continue;
|
|
219
|
+
try {
|
|
220
|
+
args[key] = JSON.parse(valRaw);
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
args[key] = valRaw;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
results.push({ name, arguments: args });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
if (results.length === 0) {
|
|
230
|
+
const fenceRegex = /```(?:tool_call|json)?\s*(\{[\s\S]*?"name"\s*:\s*[\s\S]*?\})\s*```/g;
|
|
231
|
+
let fenceMatch;
|
|
232
|
+
while ((fenceMatch = fenceRegex.exec(text)) !== null) {
|
|
233
|
+
try {
|
|
234
|
+
const parsed = JSON.parse((fenceMatch[1] || '').trim());
|
|
235
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
236
|
+
results.push(parsed);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
// ignore invalid fence
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return results;
|
|
245
|
+
}
|
|
246
|
+
export function stripToolCallMarkup(text) {
|
|
247
|
+
if (!text || typeof text !== 'string')
|
|
248
|
+
return '';
|
|
249
|
+
return text
|
|
250
|
+
.replace(/<tool_call>[\s\S]*?(?:<\/tool_call>|(?:\s*<\/?[||]DSML[||][^>]*>)+|$)/gi, '')
|
|
251
|
+
.replace(/<[||]DSML[||][\s\S]*?(?:<\/[||]DSML[||]\s*calls>|$)/gi, '')
|
|
252
|
+
.replace(/(?:\s*<\/?[||]DSML[||][^>]*>)+/gi, '')
|
|
253
|
+
.trim();
|
|
254
|
+
}
|
|
255
|
+
export function stripThinkBlocks(text) {
|
|
256
|
+
if (!text || typeof text !== 'string')
|
|
257
|
+
return '';
|
|
258
|
+
return text
|
|
259
|
+
.replace(/<(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>[\s\S]*?(?:<\/(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>|$)/gi, '')
|
|
260
|
+
.trim();
|
|
261
|
+
}
|
|
262
|
+
export function extractLivePlanFromText(text, allowTrailing = false) {
|
|
263
|
+
if (!text || typeof text !== 'string')
|
|
264
|
+
return null;
|
|
265
|
+
const cleanText = text.replace(/\r\n/g, '\n');
|
|
266
|
+
// 1. Check for inline <tool_call>{"name": "update_plan" | "todowrite", ...}</tool_call> (including DSML-closed blocks)
|
|
267
|
+
let latestToolPlan = null;
|
|
268
|
+
for (const parsed of extractToolCallJsonObjects(cleanText)) {
|
|
269
|
+
try {
|
|
270
|
+
const toolName = String(parsed?.name || parsed?.tool || '').toLowerCase().trim();
|
|
271
|
+
if (toolName === 'update_plan' || toolName === 'todowrite' || toolName === 'todo_write') {
|
|
272
|
+
const rawArgs = typeof parsed.arguments === 'string'
|
|
273
|
+
? JSON.parse(parsed.arguments)
|
|
274
|
+
: (parsed.arguments ?? parsed.parameters ?? parsed.input ?? parsed);
|
|
275
|
+
const normalized = normalizePeerPlanEntries(rawArgs);
|
|
276
|
+
if (normalized)
|
|
277
|
+
latestToolPlan = normalized;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
// Ignore partial or invalid JSON inside <tool_call>
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (latestToolPlan)
|
|
285
|
+
return latestToolPlan;
|
|
286
|
+
// 2. Check for an explicit Plan: / Implementation Plan: numbered or checkbox list in reasoning/text
|
|
287
|
+
const planHeaderRegex = /(?:^|\n)[ \t]*(?:#{1,4}[ \t]+|\*{1,2})?(?:(?:here\s+is\s+(?:the\s+)?|our\s+|my\s+|action\s+|execution\s+|implementation\s+)?(?:plan|rencana|langkah(?:-langkah)?|roadmap|steps))(?:\*{1,2})?[ \t]*:?[ \t]*\n((?:[ \t]*(?:\d+[.)]|[-*•][ \t]+\[[ xX✓▸>-]\])[ \t]+[^\n]+\n?){2,12})/gi;
|
|
288
|
+
let headerMatch;
|
|
289
|
+
let latestBlock = '';
|
|
290
|
+
let latestEndIndex = -1;
|
|
291
|
+
while ((headerMatch = planHeaderRegex.exec(cleanText)) !== null) {
|
|
292
|
+
latestBlock = headerMatch[1] || '';
|
|
293
|
+
latestEndIndex = headerMatch.index + headerMatch[0].length;
|
|
294
|
+
}
|
|
295
|
+
if (!latestBlock)
|
|
296
|
+
return null;
|
|
297
|
+
// While streaming, verify that the captured block ended cleanly with a newline
|
|
298
|
+
if (!allowTrailing && latestEndIndex > 0) {
|
|
299
|
+
const remainder = cleanText.slice(latestEndIndex);
|
|
300
|
+
if (remainder.length === 0 && !latestBlock.endsWith('\n')) {
|
|
301
|
+
return null;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
const lines = latestBlock
|
|
305
|
+
.split('\n')
|
|
306
|
+
.map(l => l.trim())
|
|
307
|
+
.filter(Boolean);
|
|
308
|
+
if (lines.length < 2)
|
|
309
|
+
return null;
|
|
310
|
+
const rawItems = [];
|
|
311
|
+
for (let i = 0; i < Math.min(lines.length, MAX_STEPS); i++) {
|
|
312
|
+
const line = lines[i];
|
|
313
|
+
const itemMatch = /^(?:(\d+)[.)]|[-*•]\s*\[([ xX✓▸>-])\])\s+(.+)$/.exec(line);
|
|
314
|
+
if (!itemMatch)
|
|
315
|
+
continue;
|
|
316
|
+
const checkMark = (itemMatch[2] || '').toLowerCase();
|
|
317
|
+
const stepText = (itemMatch[3] || '').replace(/\s+/g, ' ').trim().slice(0, 240);
|
|
318
|
+
if (!stepText || stepText.length < 4)
|
|
319
|
+
continue;
|
|
320
|
+
const status = checkMark === 'x' || checkMark === '✓'
|
|
321
|
+
? 'completed'
|
|
322
|
+
: checkMark === '>' || checkMark === '▸' || checkMark === '-'
|
|
323
|
+
? 'in_progress'
|
|
324
|
+
: 'pending';
|
|
325
|
+
rawItems.push({
|
|
326
|
+
id: `step-${rawItems.length + 1}`,
|
|
327
|
+
step: stepText,
|
|
328
|
+
status
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
if (rawItems.length < 2)
|
|
332
|
+
return null;
|
|
333
|
+
return normalizePeerPlanEntries({ plan: rawItems });
|
|
334
|
+
}
|