@caupulican/pi-adaptative 0.81.35 → 0.81.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +10 -8
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session.d.ts +5 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +17 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
- package/dist/core/autonomy/approval-gate.js +2 -0
- package/dist/core/autonomy/approval-gate.js.map +1 -1
- package/dist/core/autonomy/foreground-envelope.d.ts.map +1 -1
- package/dist/core/autonomy/foreground-envelope.js +2 -0
- package/dist/core/autonomy/foreground-envelope.js.map +1 -1
- package/dist/core/autonomy/gates.d.ts.map +1 -1
- package/dist/core/autonomy/gates.js +9 -2
- package/dist/core/autonomy/gates.js.map +1 -1
- package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
- package/dist/core/autonomy/risk-assessment.js +2 -0
- package/dist/core/autonomy/risk-assessment.js.map +1 -1
- package/dist/core/bash-execution-controller.d.ts +9 -4
- package/dist/core/bash-execution-controller.d.ts.map +1 -1
- package/dist/core/bash-execution-controller.js +7 -6
- package/dist/core/bash-execution-controller.js.map +1 -1
- package/dist/core/bash-executor.d.ts +2 -0
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +3 -2
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/default-tool-surface.d.ts +7 -0
- package/dist/core/default-tool-surface.d.ts.map +1 -1
- package/dist/core/default-tool-surface.js +29 -10
- package/dist/core/default-tool-surface.js.map +1 -1
- package/dist/core/doctor.d.ts +10 -10
- package/dist/core/doctor.d.ts.map +1 -1
- package/dist/core/doctor.js +30 -20
- package/dist/core/doctor.js.map +1 -1
- package/dist/core/exec.d.ts +2 -0
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +1 -0
- package/dist/core/exec.js.map +1 -1
- package/dist/core/extensions/types.d.ts +13 -3
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js +3 -0
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/memory/memory-manager.d.ts.map +1 -1
- package/dist/core/memory/memory-manager.js +1 -0
- package/dist/core/memory/memory-manager.js.map +1 -1
- package/dist/core/model-capability.d.ts.map +1 -1
- package/dist/core/model-capability.js +2 -0
- package/dist/core/model-capability.js.map +1 -1
- package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
- package/dist/core/model-router/tool-escalation.js +17 -3
- package/dist/core/model-router/tool-escalation.js.map +1 -1
- package/dist/core/python-runtime.d.ts +46 -0
- package/dist/core/python-runtime.d.ts.map +1 -0
- package/dist/core/python-runtime.js +157 -0
- package/dist/core/python-runtime.js.map +1 -0
- package/dist/core/runtime-builder.d.ts +4 -0
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +31 -9
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/security/untrusted-boundary.d.ts +2 -2
- package/dist/core/security/untrusted-boundary.d.ts.map +1 -1
- package/dist/core/security/untrusted-boundary.js +4 -3
- package/dist/core/security/untrusted-boundary.js.map +1 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +2 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +8 -0
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +13 -2
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tasks/session-task-state.d.ts +10 -0
- package/dist/core/tasks/session-task-state.d.ts.map +1 -0
- package/dist/core/tasks/session-task-state.js +29 -0
- package/dist/core/tasks/session-task-state.js.map +1 -0
- package/dist/core/tasks/task-command.d.ts +30 -0
- package/dist/core/tasks/task-command.d.ts.map +1 -0
- package/dist/core/tasks/task-command.js +79 -0
- package/dist/core/tasks/task-command.js.map +1 -0
- package/dist/core/tasks/task-state.d.ts +71 -0
- package/dist/core/tasks/task-state.d.ts.map +1 -0
- package/dist/core/tasks/task-state.js +372 -0
- package/dist/core/tasks/task-state.js.map +1 -0
- package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -1
- package/dist/core/tool-selection/tool-selection-controller.js +1 -1
- package/dist/core/tool-selection/tool-selection-controller.js.map +1 -1
- package/dist/core/tools/bash.d.ts +20 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +122 -197
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +3 -0
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +3 -0
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +9 -6
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +24 -9
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/python.d.ts +64 -0
- package/dist/core/tools/python.d.ts.map +1 -0
- package/dist/core/tools/python.js +241 -0
- package/dist/core/tools/python.js.map +1 -0
- package/dist/core/tools/shell-contract-router.d.ts +13 -0
- package/dist/core/tools/shell-contract-router.d.ts.map +1 -0
- package/dist/core/tools/shell-contract-router.js +295 -0
- package/dist/core/tools/shell-contract-router.js.map +1 -0
- package/dist/core/tools/task-steps.d.ts +46 -0
- package/dist/core/tools/task-steps.d.ts.map +1 -0
- package/dist/core/tools/task-steps.js +160 -0
- package/dist/core/tools/task-steps.js.map +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +12 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/session-flow-commands.d.ts +10 -0
- package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
- package/dist/modes/interactive/session-flow-commands.js +43 -0
- package/dist/modes/interactive/session-flow-commands.js.map +1 -1
- package/dist/utils/shell.d.ts +6 -8
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +61 -70
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/tools-manager.d.ts +23 -3
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +94 -11
- package/dist/utils/tools-manager.js.map +1 -1
- package/docs/index.md +2 -0
- package/docs/python.md +43 -0
- package/docs/settings.md +7 -3
- package/docs/task-steps.md +90 -0
- package/docs/termux.md +7 -0
- package/docs/usage.md +5 -6
- package/docs/windows.md +15 -12
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +32 -37
- package/package.json +9 -7
- package/scripts/postinstall-python-runtime.mjs +20 -0
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
export const TASK_STEP_STATUSES = ["pending", "in_progress", "completed", "blocked", "cancelled"];
|
|
2
|
+
export const TASK_STEP_PRIORITIES = ["low", "normal", "high"];
|
|
3
|
+
export const MAX_TASK_STEPS = 100;
|
|
4
|
+
export const MAX_TASK_STEP_CONTENT_LENGTH = 2_000;
|
|
5
|
+
const MAX_TASK_STEP_NOTE_LENGTH = 4_000;
|
|
6
|
+
const MAX_TASK_STEP_OWNER_LENGTH = 200;
|
|
7
|
+
const MAX_TASK_STEP_EVIDENCE = 32;
|
|
8
|
+
const MAX_TASK_STEP_EVIDENCE_LENGTH = 2_000;
|
|
9
|
+
export class TaskStepsError extends Error {
|
|
10
|
+
constructor(message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = "TaskStepsError";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function isRecord(value) {
|
|
16
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
17
|
+
return false;
|
|
18
|
+
const prototype = Object.getPrototypeOf(value);
|
|
19
|
+
return prototype === Object.prototype || prototype === null;
|
|
20
|
+
}
|
|
21
|
+
function isTaskStepStatus(value) {
|
|
22
|
+
return TASK_STEP_STATUSES.some((status) => status === value);
|
|
23
|
+
}
|
|
24
|
+
function isTaskStepPriority(value) {
|
|
25
|
+
return TASK_STEP_PRIORITIES.some((priority) => priority === value);
|
|
26
|
+
}
|
|
27
|
+
function hasOptionalString(record, key, maxLength) {
|
|
28
|
+
const value = record[key];
|
|
29
|
+
return value === undefined || (typeof value === "string" && value.length <= maxLength);
|
|
30
|
+
}
|
|
31
|
+
function isBoundedStringArray(value, maxItems, maxLength) {
|
|
32
|
+
return (Array.isArray(value) &&
|
|
33
|
+
value.length <= maxItems &&
|
|
34
|
+
value.every((item) => typeof item === "string" && item.length > 0 && item.length <= maxLength));
|
|
35
|
+
}
|
|
36
|
+
function isTaskStep(value) {
|
|
37
|
+
if (!isRecord(value))
|
|
38
|
+
return false;
|
|
39
|
+
return (typeof value.id === "string" &&
|
|
40
|
+
/^step-[1-9]\d*$/.test(value.id) &&
|
|
41
|
+
typeof value.content === "string" &&
|
|
42
|
+
value.content.length > 0 &&
|
|
43
|
+
value.content.length <= MAX_TASK_STEP_CONTENT_LENGTH &&
|
|
44
|
+
hasOptionalString(value, "activeForm", MAX_TASK_STEP_CONTENT_LENGTH) &&
|
|
45
|
+
isTaskStepStatus(value.status) &&
|
|
46
|
+
(value.priority === undefined || isTaskStepPriority(value.priority)) &&
|
|
47
|
+
hasOptionalString(value, "owner", MAX_TASK_STEP_OWNER_LENGTH) &&
|
|
48
|
+
isBoundedStringArray(value.notes, MAX_TASK_STEP_EVIDENCE, MAX_TASK_STEP_NOTE_LENGTH) &&
|
|
49
|
+
isBoundedStringArray(value.evidence, MAX_TASK_STEP_EVIDENCE, MAX_TASK_STEP_EVIDENCE_LENGTH) &&
|
|
50
|
+
typeof value.createdAt === "string" &&
|
|
51
|
+
typeof value.updatedAt === "string");
|
|
52
|
+
}
|
|
53
|
+
function isTaskStepsArchive(value) {
|
|
54
|
+
if (!isRecord(value))
|
|
55
|
+
return false;
|
|
56
|
+
return (Number.isInteger(value.completed) &&
|
|
57
|
+
Number(value.completed) >= 0 &&
|
|
58
|
+
Number.isInteger(value.cancelled) &&
|
|
59
|
+
Number(value.cancelled) >= 0 &&
|
|
60
|
+
hasOptionalString(value, "compactedAt", 100));
|
|
61
|
+
}
|
|
62
|
+
export function isTaskStepsState(value) {
|
|
63
|
+
if (!isRecord(value))
|
|
64
|
+
return false;
|
|
65
|
+
if (value.version !== 1 ||
|
|
66
|
+
!Number.isInteger(value.revision) ||
|
|
67
|
+
Number(value.revision) < 0 ||
|
|
68
|
+
!Number.isInteger(value.nextStepNumber) ||
|
|
69
|
+
Number(value.nextStepNumber) < 1 ||
|
|
70
|
+
!Array.isArray(value.steps) ||
|
|
71
|
+
value.steps.length > MAX_TASK_STEPS ||
|
|
72
|
+
!value.steps.every(isTaskStep) ||
|
|
73
|
+
!isTaskStepsArchive(value.archive) ||
|
|
74
|
+
typeof value.createdAt !== "string" ||
|
|
75
|
+
typeof value.updatedAt !== "string") {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
const ids = new Set(value.steps.map((step) => step.id));
|
|
79
|
+
return ids.size === value.steps.length && value.steps.filter((step) => step.status === "in_progress").length <= 1;
|
|
80
|
+
}
|
|
81
|
+
function cloneTaskStep(step) {
|
|
82
|
+
return { ...step, notes: [...step.notes], evidence: [...step.evidence] };
|
|
83
|
+
}
|
|
84
|
+
export function cloneTaskStepsState(state) {
|
|
85
|
+
return {
|
|
86
|
+
...state,
|
|
87
|
+
steps: state.steps.map(cloneTaskStep),
|
|
88
|
+
archive: { ...state.archive },
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
export function createTaskStepsState(now) {
|
|
92
|
+
return {
|
|
93
|
+
version: 1,
|
|
94
|
+
revision: 0,
|
|
95
|
+
nextStepNumber: 1,
|
|
96
|
+
steps: [],
|
|
97
|
+
archive: { completed: 0, cancelled: 0 },
|
|
98
|
+
createdAt: now,
|
|
99
|
+
updatedAt: now,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function requireBoundedText(value, label, maxLength) {
|
|
103
|
+
const normalized = value.trim();
|
|
104
|
+
if (!normalized)
|
|
105
|
+
throw new TaskStepsError(`${label} is required.`);
|
|
106
|
+
if (normalized.length > maxLength)
|
|
107
|
+
throw new TaskStepsError(`${label} must be at most ${maxLength} characters.`);
|
|
108
|
+
return normalized;
|
|
109
|
+
}
|
|
110
|
+
function optionalBoundedText(value, label, maxLength) {
|
|
111
|
+
if (value === undefined)
|
|
112
|
+
return undefined;
|
|
113
|
+
const normalized = value.trim();
|
|
114
|
+
if (!normalized)
|
|
115
|
+
return undefined;
|
|
116
|
+
if (normalized.length > maxLength)
|
|
117
|
+
throw new TaskStepsError(`${label} must be at most ${maxLength} characters.`);
|
|
118
|
+
return normalized;
|
|
119
|
+
}
|
|
120
|
+
function normalizeStrings(values, label, maxLength) {
|
|
121
|
+
if (!values)
|
|
122
|
+
return [];
|
|
123
|
+
const normalized = [];
|
|
124
|
+
for (const value of values) {
|
|
125
|
+
const item = requireBoundedText(value, label, maxLength);
|
|
126
|
+
if (!normalized.includes(item))
|
|
127
|
+
normalized.push(item);
|
|
128
|
+
}
|
|
129
|
+
if (normalized.length > MAX_TASK_STEP_EVIDENCE) {
|
|
130
|
+
throw new TaskStepsError(`${label} supports at most ${MAX_TASK_STEP_EVIDENCE} entries.`);
|
|
131
|
+
}
|
|
132
|
+
return normalized;
|
|
133
|
+
}
|
|
134
|
+
function appendUniqueStrings(current, values, label, maxLength) {
|
|
135
|
+
const appended = [...current];
|
|
136
|
+
for (const value of normalizeStrings(values, label, maxLength)) {
|
|
137
|
+
if (!appended.includes(value))
|
|
138
|
+
appended.push(value);
|
|
139
|
+
}
|
|
140
|
+
if (appended.length > MAX_TASK_STEP_EVIDENCE) {
|
|
141
|
+
throw new TaskStepsError(`${label} supports at most ${MAX_TASK_STEP_EVIDENCE} entries.`);
|
|
142
|
+
}
|
|
143
|
+
return appended;
|
|
144
|
+
}
|
|
145
|
+
function normalizeInputNotes(input) {
|
|
146
|
+
const notes = normalizeStrings(input.notes, "Task step note", MAX_TASK_STEP_NOTE_LENGTH);
|
|
147
|
+
const note = optionalBoundedText(input.note, "Task step note", MAX_TASK_STEP_NOTE_LENGTH);
|
|
148
|
+
if (note && !notes.includes(note))
|
|
149
|
+
notes.push(note);
|
|
150
|
+
return notes;
|
|
151
|
+
}
|
|
152
|
+
function demoteOtherActiveSteps(steps, activeIndex) {
|
|
153
|
+
for (let index = 0; index < steps.length; index++) {
|
|
154
|
+
if (index !== activeIndex && steps[index].status === "in_progress") {
|
|
155
|
+
steps[index] = { ...steps[index], status: "pending" };
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
function nextState(state, steps, now) {
|
|
160
|
+
return {
|
|
161
|
+
...state,
|
|
162
|
+
revision: state.revision + 1,
|
|
163
|
+
steps: steps.map(cloneTaskStep),
|
|
164
|
+
archive: { ...state.archive },
|
|
165
|
+
updatedAt: now,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
function createStep(args) {
|
|
169
|
+
const existing = args.existing;
|
|
170
|
+
const notes = args.input.note === undefined && args.input.notes === undefined
|
|
171
|
+
? [...(existing?.notes ?? [])]
|
|
172
|
+
: normalizeInputNotes(args.input);
|
|
173
|
+
const evidence = args.input.evidence === undefined
|
|
174
|
+
? [...(existing?.evidence ?? [])]
|
|
175
|
+
: normalizeStrings(args.input.evidence, "Task step evidence", MAX_TASK_STEP_EVIDENCE_LENGTH);
|
|
176
|
+
return {
|
|
177
|
+
id: args.id,
|
|
178
|
+
content: requireBoundedText(args.input.content, "Task step content", MAX_TASK_STEP_CONTENT_LENGTH),
|
|
179
|
+
activeForm: args.input.activeForm === undefined
|
|
180
|
+
? existing?.activeForm
|
|
181
|
+
: optionalBoundedText(args.input.activeForm, "Task step active form", MAX_TASK_STEP_CONTENT_LENGTH),
|
|
182
|
+
status: args.input.status ?? existing?.status ?? "pending",
|
|
183
|
+
priority: args.input.priority ?? existing?.priority,
|
|
184
|
+
owner: args.input.owner === undefined
|
|
185
|
+
? existing?.owner
|
|
186
|
+
: optionalBoundedText(args.input.owner, "Task step owner", MAX_TASK_STEP_OWNER_LENGTH),
|
|
187
|
+
notes,
|
|
188
|
+
evidence,
|
|
189
|
+
createdAt: args.createdAt,
|
|
190
|
+
updatedAt: args.updatedAt,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
export function setTaskSteps(state, inputs, now) {
|
|
194
|
+
if (inputs.length > MAX_TASK_STEPS) {
|
|
195
|
+
throw new TaskStepsError(`Task steps supports at most ${MAX_TASK_STEPS} steps.`);
|
|
196
|
+
}
|
|
197
|
+
const existingByContent = new Map();
|
|
198
|
+
for (const step of state.steps) {
|
|
199
|
+
const key = step.content.toLocaleLowerCase();
|
|
200
|
+
const matches = existingByContent.get(key) ?? [];
|
|
201
|
+
matches.push(step);
|
|
202
|
+
existingByContent.set(key, matches);
|
|
203
|
+
}
|
|
204
|
+
let nextStepNumber = state.nextStepNumber;
|
|
205
|
+
const steps = inputs.map((input) => {
|
|
206
|
+
const content = requireBoundedText(input.content, "Task step content", MAX_TASK_STEP_CONTENT_LENGTH);
|
|
207
|
+
const matches = existingByContent.get(content.toLocaleLowerCase());
|
|
208
|
+
const existing = matches?.shift();
|
|
209
|
+
const id = existing?.id ?? `step-${nextStepNumber++}`;
|
|
210
|
+
return createStep({
|
|
211
|
+
input: { ...input, content },
|
|
212
|
+
id,
|
|
213
|
+
createdAt: existing?.createdAt ?? now,
|
|
214
|
+
updatedAt: now,
|
|
215
|
+
existing,
|
|
216
|
+
});
|
|
217
|
+
});
|
|
218
|
+
const activeIndex = steps.findLastIndex((step) => step.status === "in_progress");
|
|
219
|
+
if (activeIndex >= 0)
|
|
220
|
+
demoteOtherActiveSteps(steps, activeIndex);
|
|
221
|
+
return { ...nextState(state, steps, now), nextStepNumber };
|
|
222
|
+
}
|
|
223
|
+
export function addTaskStep(state, input, now) {
|
|
224
|
+
if (state.steps.length >= MAX_TASK_STEPS) {
|
|
225
|
+
throw new TaskStepsError(`Task steps already has the maximum ${MAX_TASK_STEPS} steps.`);
|
|
226
|
+
}
|
|
227
|
+
const step = createStep({ input, id: `step-${state.nextStepNumber}`, createdAt: now, updatedAt: now });
|
|
228
|
+
const steps = [...state.steps.map(cloneTaskStep), step];
|
|
229
|
+
if (step.status === "in_progress")
|
|
230
|
+
demoteOtherActiveSteps(steps, steps.length - 1);
|
|
231
|
+
return { ...nextState(state, steps, now), nextStepNumber: state.nextStepNumber + 1 };
|
|
232
|
+
}
|
|
233
|
+
export function resolveTaskStepSelector(steps, selector) {
|
|
234
|
+
const normalized = selector.trim().toLocaleLowerCase();
|
|
235
|
+
if (!normalized)
|
|
236
|
+
throw new TaskStepsError("Task step selector is required.");
|
|
237
|
+
if (normalized === "current" || normalized === "active") {
|
|
238
|
+
const active = steps.find((step) => step.status === "in_progress");
|
|
239
|
+
if (!active)
|
|
240
|
+
throw new TaskStepsError("No in_progress task step was found.");
|
|
241
|
+
return active;
|
|
242
|
+
}
|
|
243
|
+
const exactId = steps.find((step) => step.id.toLocaleLowerCase() === normalized);
|
|
244
|
+
if (exactId)
|
|
245
|
+
return exactId;
|
|
246
|
+
const idPrefix = steps.filter((step) => step.id.toLocaleLowerCase().startsWith(normalized));
|
|
247
|
+
if (idPrefix.length === 1)
|
|
248
|
+
return idPrefix[0];
|
|
249
|
+
if (idPrefix.length > 1) {
|
|
250
|
+
throw new TaskStepsError(`Task step selector is ambiguous: ${idPrefix.map((step) => step.id).join(", ")}.`);
|
|
251
|
+
}
|
|
252
|
+
const exactContent = steps.filter((step) => step.content.toLocaleLowerCase() === normalized);
|
|
253
|
+
if (exactContent.length === 1)
|
|
254
|
+
return exactContent[0];
|
|
255
|
+
const contentMatches = steps.filter((step) => step.content.toLocaleLowerCase().includes(normalized));
|
|
256
|
+
if (contentMatches.length === 1)
|
|
257
|
+
return contentMatches[0];
|
|
258
|
+
if (exactContent.length > 1 || contentMatches.length > 1) {
|
|
259
|
+
const matches = exactContent.length > 1 ? exactContent : contentMatches;
|
|
260
|
+
throw new TaskStepsError(`Task step selector is ambiguous: ${matches.map((step) => step.id).join(", ")}.`);
|
|
261
|
+
}
|
|
262
|
+
throw new TaskStepsError(`Task step not found for selector: ${selector}.`);
|
|
263
|
+
}
|
|
264
|
+
export function updateTaskStep(state, selector, update, now) {
|
|
265
|
+
const selected = resolveTaskStepSelector(state.steps, selector);
|
|
266
|
+
const selectedIndex = state.steps.findIndex((step) => step.id === selected.id);
|
|
267
|
+
const steps = state.steps.map(cloneTaskStep);
|
|
268
|
+
const current = steps[selectedIndex];
|
|
269
|
+
const note = optionalBoundedText(update.note, "Task step note", MAX_TASK_STEP_NOTE_LENGTH);
|
|
270
|
+
const notes = note
|
|
271
|
+
? appendUniqueStrings(current.notes, [note], "Task step note", MAX_TASK_STEP_NOTE_LENGTH)
|
|
272
|
+
: [...current.notes];
|
|
273
|
+
const evidence = appendUniqueStrings(current.evidence, update.evidence, "Task step evidence", MAX_TASK_STEP_EVIDENCE_LENGTH);
|
|
274
|
+
steps[selectedIndex] = {
|
|
275
|
+
...current,
|
|
276
|
+
content: update.content === undefined
|
|
277
|
+
? current.content
|
|
278
|
+
: requireBoundedText(update.content, "Task step content", MAX_TASK_STEP_CONTENT_LENGTH),
|
|
279
|
+
activeForm: update.activeForm === undefined
|
|
280
|
+
? current.activeForm
|
|
281
|
+
: optionalBoundedText(update.activeForm, "Task step active form", MAX_TASK_STEP_CONTENT_LENGTH),
|
|
282
|
+
status: update.status ?? current.status,
|
|
283
|
+
priority: update.priority ?? current.priority,
|
|
284
|
+
owner: update.owner === undefined
|
|
285
|
+
? current.owner
|
|
286
|
+
: optionalBoundedText(update.owner, "Task step owner", MAX_TASK_STEP_OWNER_LENGTH),
|
|
287
|
+
notes,
|
|
288
|
+
evidence,
|
|
289
|
+
updatedAt: now,
|
|
290
|
+
};
|
|
291
|
+
if (steps[selectedIndex].status === "in_progress")
|
|
292
|
+
demoteOtherActiveSteps(steps, selectedIndex);
|
|
293
|
+
return nextState(state, steps, now);
|
|
294
|
+
}
|
|
295
|
+
export function clearTaskSteps(state, now) {
|
|
296
|
+
return {
|
|
297
|
+
...nextState(state, [], now),
|
|
298
|
+
archive: { completed: 0, cancelled: 0 },
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
export function compactTaskSteps(state, now) {
|
|
302
|
+
const completed = state.steps.filter((step) => step.status === "completed").length;
|
|
303
|
+
const cancelled = state.steps.filter((step) => step.status === "cancelled").length;
|
|
304
|
+
const open = state.steps.filter((step) => step.status !== "completed" && step.status !== "cancelled");
|
|
305
|
+
return {
|
|
306
|
+
...nextState(state, open, now),
|
|
307
|
+
archive: {
|
|
308
|
+
completed: state.archive.completed + completed,
|
|
309
|
+
cancelled: state.archive.cancelled + cancelled,
|
|
310
|
+
compactedAt: now,
|
|
311
|
+
},
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
export function formatTaskSteps(state, options = {}) {
|
|
315
|
+
const visible = options.includeTerminal
|
|
316
|
+
? state.steps
|
|
317
|
+
: state.steps.filter((step) => step.status !== "completed" && step.status !== "cancelled");
|
|
318
|
+
const maxItems = Math.max(1, Math.min(MAX_TASK_STEPS, Math.floor(options.maxItems ?? 20)));
|
|
319
|
+
const statusMarker = {
|
|
320
|
+
pending: " ",
|
|
321
|
+
in_progress: ">",
|
|
322
|
+
completed: "x",
|
|
323
|
+
blocked: "!",
|
|
324
|
+
cancelled: "-",
|
|
325
|
+
};
|
|
326
|
+
const lines = [`Task steps (${visible.length} visible, ${state.steps.length} tracked):`];
|
|
327
|
+
for (const step of visible.slice(0, maxItems)) {
|
|
328
|
+
const details = [step.priority, step.owner].filter(Boolean).join(", ");
|
|
329
|
+
lines.push(`- [${statusMarker[step.status]}] ${step.id} ${step.activeForm || step.content}${details ? ` (${details})` : ""}`);
|
|
330
|
+
for (const note of step.notes.slice(-2))
|
|
331
|
+
lines.push(` note: ${note}`);
|
|
332
|
+
for (const evidence of step.evidence.slice(-2))
|
|
333
|
+
lines.push(` evidence: ${evidence}`);
|
|
334
|
+
}
|
|
335
|
+
if (visible.length > maxItems)
|
|
336
|
+
lines.push(`- … ${visible.length - maxItems} more`);
|
|
337
|
+
if (state.archive.completed || state.archive.cancelled) {
|
|
338
|
+
lines.push(`Archived terminal steps: ${state.archive.completed} completed, ${state.archive.cancelled} cancelled.`);
|
|
339
|
+
}
|
|
340
|
+
return lines.join("\n");
|
|
341
|
+
}
|
|
342
|
+
export function formatTaskStepsContext(state, maxItems = 12) {
|
|
343
|
+
const open = state.steps.filter((step) => step.status !== "completed" && step.status !== "cancelled");
|
|
344
|
+
if (open.length === 0)
|
|
345
|
+
return undefined;
|
|
346
|
+
const limit = Math.max(1, Math.min(MAX_TASK_STEPS, Math.floor(maxItems)));
|
|
347
|
+
const lines = [
|
|
348
|
+
"Current native task_steps context for this session:",
|
|
349
|
+
"Open task_steps:",
|
|
350
|
+
...open.slice(0, limit).map((step) => `- [${step.status}] ${step.activeForm || step.content}`),
|
|
351
|
+
];
|
|
352
|
+
if (open.length > limit)
|
|
353
|
+
lines.push(`- … ${open.length - limit} more open step(s)`);
|
|
354
|
+
const active = open.find((step) => step.status === "in_progress");
|
|
355
|
+
lines.push("", active
|
|
356
|
+
? `Continue the in_progress step first: ${active.activeForm || active.content}. Update it completed, blocked, or cancelled as soon as evidence is known.`
|
|
357
|
+
: `No step is in_progress. Start the first open step before unrelated work: ${open[0].activeForm || open[0].content}.`, "Use task_steps to keep this checklist current and leave no stale in_progress step before the final response.");
|
|
358
|
+
return lines.join("\n");
|
|
359
|
+
}
|
|
360
|
+
export function serializeTaskStepsState(state) {
|
|
361
|
+
return JSON.stringify(cloneTaskStepsState(state), null, 2);
|
|
362
|
+
}
|
|
363
|
+
export function parseTaskStepsState(text) {
|
|
364
|
+
try {
|
|
365
|
+
const parsed = JSON.parse(text);
|
|
366
|
+
return isTaskStepsState(parsed) ? cloneTaskStepsState(parsed) : undefined;
|
|
367
|
+
}
|
|
368
|
+
catch {
|
|
369
|
+
return undefined;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
//# sourceMappingURL=task-state.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"task-state.js","sourceRoot":"","sources":["../../../src/core/tasks/task-state.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,SAAS,EAAE,aAAa,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW,CAAU,CAAC;AAG3G,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAU,CAAC;AAGvE,MAAM,CAAC,MAAM,cAAc,GAAG,GAAG,CAAC;AAClC,MAAM,CAAC,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAClD,MAAM,yBAAyB,GAAG,KAAK,CAAC;AACxC,MAAM,0BAA0B,GAAG,GAAG,CAAC;AACvC,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAClC,MAAM,6BAA6B,GAAG,KAAK,CAAC;AAoD5C,MAAM,OAAO,cAAe,SAAQ,KAAK;IACxC,YAAY,OAAe,EAAE;QAC5B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAAA,CAC7B;CACD;AAED,SAAS,QAAQ,CAAC,KAAc,EAAoC;IACnE,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IA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AAG,KAAK,oBAAoB,CAAC,CAAC;IACpF,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,KAAK,aAAa,CAAC,CAAC;IAClE,KAAK,CAAC,IAAI,CACT,EAAE,EACF,MAAM;QACL,CAAC,CAAC,wCAAwC,MAAM,CAAC,UAAU,IAAI,MAAM,CAAC,OAAO,4EAA4E;QACzJ,CAAC,CAAC,4EAA4E,IAAI,CAAC,CAAC,CAAC,CAAC,UAAU,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,GAAG,EACvH,8GAA8G,CAC9G,CAAC;IACF,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACxB;AAED,MAAM,UAAU,uBAAuB,CAAC,KAAqB,EAAU;IACtE,OAAO,IAAI,CAAC,SAAS,CAAC,mBAAmB,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AAAA,CAC3D;AAED,MAAM,UAAU,mBAAmB,CAAC,IAAY,EAA8B;IAC7E,IAAI,CAAC;QACJ,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACzC,OAAO,gBAAgB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC3E,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["export const TASK_STEP_STATUSES = [\"pending\", \"in_progress\", \"completed\", \"blocked\", \"cancelled\"] as const;\nexport type TaskStepStatus = (typeof TASK_STEP_STATUSES)[number];\n\nexport const TASK_STEP_PRIORITIES = [\"low\", \"normal\", \"high\"] as const;\nexport type TaskStepPriority = (typeof TASK_STEP_PRIORITIES)[number];\n\nexport const MAX_TASK_STEPS = 100;\nexport const MAX_TASK_STEP_CONTENT_LENGTH = 2_000;\nconst MAX_TASK_STEP_NOTE_LENGTH = 4_000;\nconst MAX_TASK_STEP_OWNER_LENGTH = 200;\nconst MAX_TASK_STEP_EVIDENCE = 32;\nconst MAX_TASK_STEP_EVIDENCE_LENGTH = 2_000;\n\nexport interface TaskStepInput {\n\tcontent: string;\n\tactiveForm?: string;\n\tstatus?: TaskStepStatus;\n\tpriority?: TaskStepPriority;\n\towner?: string;\n\tnote?: string;\n\tnotes?: readonly string[];\n\tevidence?: readonly string[];\n}\n\nexport interface TaskStep {\n\tid: string;\n\tcontent: string;\n\tactiveForm?: string;\n\tstatus: TaskStepStatus;\n\tpriority?: TaskStepPriority;\n\towner?: string;\n\tnotes: readonly string[];\n\tevidence: readonly string[];\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nexport interface TaskStepsArchive {\n\tcompleted: number;\n\tcancelled: number;\n\tcompactedAt?: string;\n}\n\nexport interface TaskStepsState {\n\tversion: 1;\n\trevision: number;\n\tnextStepNumber: number;\n\tsteps: readonly TaskStep[];\n\tarchive: TaskStepsArchive;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nexport interface TaskStepUpdate {\n\tcontent?: string;\n\tactiveForm?: string;\n\tstatus?: TaskStepStatus;\n\tpriority?: TaskStepPriority;\n\towner?: string;\n\tnote?: string;\n\tevidence?: readonly string[];\n}\n\nexport class TaskStepsError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"TaskStepsError\";\n\t}\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction isTaskStepStatus(value: unknown): value is TaskStepStatus {\n\treturn TASK_STEP_STATUSES.some((status) => status === value);\n}\n\nfunction isTaskStepPriority(value: unknown): value is TaskStepPriority {\n\treturn TASK_STEP_PRIORITIES.some((priority) => priority === value);\n}\n\nfunction hasOptionalString(record: Record<string, unknown>, key: string, maxLength: number): boolean {\n\tconst value = record[key];\n\treturn value === undefined || (typeof value === \"string\" && value.length <= maxLength);\n}\n\nfunction isBoundedStringArray(value: unknown, maxItems: number, maxLength: number): value is readonly string[] {\n\treturn (\n\t\tArray.isArray(value) &&\n\t\tvalue.length <= maxItems &&\n\t\tvalue.every((item) => typeof item === \"string\" && item.length > 0 && item.length <= maxLength)\n\t);\n}\n\nfunction isTaskStep(value: unknown): value is TaskStep {\n\tif (!isRecord(value)) return false;\n\treturn (\n\t\ttypeof value.id === \"string\" &&\n\t\t/^step-[1-9]\\d*$/.test(value.id) &&\n\t\ttypeof value.content === \"string\" &&\n\t\tvalue.content.length > 0 &&\n\t\tvalue.content.length <= MAX_TASK_STEP_CONTENT_LENGTH &&\n\t\thasOptionalString(value, \"activeForm\", MAX_TASK_STEP_CONTENT_LENGTH) &&\n\t\tisTaskStepStatus(value.status) &&\n\t\t(value.priority === undefined || isTaskStepPriority(value.priority)) &&\n\t\thasOptionalString(value, \"owner\", MAX_TASK_STEP_OWNER_LENGTH) &&\n\t\tisBoundedStringArray(value.notes, MAX_TASK_STEP_EVIDENCE, MAX_TASK_STEP_NOTE_LENGTH) &&\n\t\tisBoundedStringArray(value.evidence, MAX_TASK_STEP_EVIDENCE, MAX_TASK_STEP_EVIDENCE_LENGTH) &&\n\t\ttypeof value.createdAt === \"string\" &&\n\t\ttypeof value.updatedAt === \"string\"\n\t);\n}\n\nfunction isTaskStepsArchive(value: unknown): value is TaskStepsArchive {\n\tif (!isRecord(value)) return false;\n\treturn (\n\t\tNumber.isInteger(value.completed) &&\n\t\tNumber(value.completed) >= 0 &&\n\t\tNumber.isInteger(value.cancelled) &&\n\t\tNumber(value.cancelled) >= 0 &&\n\t\thasOptionalString(value, \"compactedAt\", 100)\n\t);\n}\n\nexport function isTaskStepsState(value: unknown): value is TaskStepsState {\n\tif (!isRecord(value)) return false;\n\tif (\n\t\tvalue.version !== 1 ||\n\t\t!Number.isInteger(value.revision) ||\n\t\tNumber(value.revision) < 0 ||\n\t\t!Number.isInteger(value.nextStepNumber) ||\n\t\tNumber(value.nextStepNumber) < 1 ||\n\t\t!Array.isArray(value.steps) ||\n\t\tvalue.steps.length > MAX_TASK_STEPS ||\n\t\t!value.steps.every(isTaskStep) ||\n\t\t!isTaskStepsArchive(value.archive) ||\n\t\ttypeof value.createdAt !== \"string\" ||\n\t\ttypeof value.updatedAt !== \"string\"\n\t) {\n\t\treturn false;\n\t}\n\tconst ids = new Set(value.steps.map((step) => step.id));\n\treturn ids.size === value.steps.length && value.steps.filter((step) => step.status === \"in_progress\").length <= 1;\n}\n\nfunction cloneTaskStep(step: TaskStep): TaskStep {\n\treturn { ...step, notes: [...step.notes], evidence: [...step.evidence] };\n}\n\nexport function cloneTaskStepsState(state: TaskStepsState): TaskStepsState {\n\treturn {\n\t\t...state,\n\t\tsteps: state.steps.map(cloneTaskStep),\n\t\tarchive: { ...state.archive },\n\t};\n}\n\nexport function createTaskStepsState(now: string): TaskStepsState {\n\treturn {\n\t\tversion: 1,\n\t\trevision: 0,\n\t\tnextStepNumber: 1,\n\t\tsteps: [],\n\t\tarchive: { completed: 0, cancelled: 0 },\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t};\n}\n\nfunction requireBoundedText(value: string, label: string, maxLength: number): string {\n\tconst normalized = value.trim();\n\tif (!normalized) throw new TaskStepsError(`${label} is required.`);\n\tif (normalized.length > maxLength) throw new TaskStepsError(`${label} must be at most ${maxLength} characters.`);\n\treturn normalized;\n}\n\nfunction optionalBoundedText(value: string | undefined, label: string, maxLength: number): string | undefined {\n\tif (value === undefined) return undefined;\n\tconst normalized = value.trim();\n\tif (!normalized) return undefined;\n\tif (normalized.length > maxLength) throw new TaskStepsError(`${label} must be at most ${maxLength} characters.`);\n\treturn normalized;\n}\n\nfunction normalizeStrings(values: readonly string[] | undefined, label: string, maxLength: number): string[] {\n\tif (!values) return [];\n\tconst normalized: string[] = [];\n\tfor (const value of values) {\n\t\tconst item = requireBoundedText(value, label, maxLength);\n\t\tif (!normalized.includes(item)) normalized.push(item);\n\t}\n\tif (normalized.length > MAX_TASK_STEP_EVIDENCE) {\n\t\tthrow new TaskStepsError(`${label} supports at most ${MAX_TASK_STEP_EVIDENCE} entries.`);\n\t}\n\treturn normalized;\n}\n\nfunction appendUniqueStrings(\n\tcurrent: readonly string[],\n\tvalues: readonly string[] | undefined,\n\tlabel: string,\n\tmaxLength: number,\n): string[] {\n\tconst appended = [...current];\n\tfor (const value of normalizeStrings(values, label, maxLength)) {\n\t\tif (!appended.includes(value)) appended.push(value);\n\t}\n\tif (appended.length > MAX_TASK_STEP_EVIDENCE) {\n\t\tthrow new TaskStepsError(`${label} supports at most ${MAX_TASK_STEP_EVIDENCE} entries.`);\n\t}\n\treturn appended;\n}\n\nfunction normalizeInputNotes(input: TaskStepInput): string[] {\n\tconst notes = normalizeStrings(input.notes, \"Task step note\", MAX_TASK_STEP_NOTE_LENGTH);\n\tconst note = optionalBoundedText(input.note, \"Task step note\", MAX_TASK_STEP_NOTE_LENGTH);\n\tif (note && !notes.includes(note)) notes.push(note);\n\treturn notes;\n}\n\nfunction demoteOtherActiveSteps(steps: TaskStep[], activeIndex: number): void {\n\tfor (let index = 0; index < steps.length; index++) {\n\t\tif (index !== activeIndex && steps[index].status === \"in_progress\") {\n\t\t\tsteps[index] = { ...steps[index], status: \"pending\" };\n\t\t}\n\t}\n}\n\nfunction nextState(state: TaskStepsState, steps: readonly TaskStep[], now: string): TaskStepsState {\n\treturn {\n\t\t...state,\n\t\trevision: state.revision + 1,\n\t\tsteps: steps.map(cloneTaskStep),\n\t\tarchive: { ...state.archive },\n\t\tupdatedAt: now,\n\t};\n}\n\nfunction createStep(args: {\n\tinput: TaskStepInput;\n\tid: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\texisting?: TaskStep;\n}): TaskStep {\n\tconst existing = args.existing;\n\tconst notes =\n\t\targs.input.note === undefined && args.input.notes === undefined\n\t\t\t? [...(existing?.notes ?? [])]\n\t\t\t: normalizeInputNotes(args.input);\n\tconst evidence =\n\t\targs.input.evidence === undefined\n\t\t\t? [...(existing?.evidence ?? [])]\n\t\t\t: normalizeStrings(args.input.evidence, \"Task step evidence\", MAX_TASK_STEP_EVIDENCE_LENGTH);\n\treturn {\n\t\tid: args.id,\n\t\tcontent: requireBoundedText(args.input.content, \"Task step content\", MAX_TASK_STEP_CONTENT_LENGTH),\n\t\tactiveForm:\n\t\t\targs.input.activeForm === undefined\n\t\t\t\t? existing?.activeForm\n\t\t\t\t: optionalBoundedText(args.input.activeForm, \"Task step active form\", MAX_TASK_STEP_CONTENT_LENGTH),\n\t\tstatus: args.input.status ?? existing?.status ?? \"pending\",\n\t\tpriority: args.input.priority ?? existing?.priority,\n\t\towner:\n\t\t\targs.input.owner === undefined\n\t\t\t\t? existing?.owner\n\t\t\t\t: optionalBoundedText(args.input.owner, \"Task step owner\", MAX_TASK_STEP_OWNER_LENGTH),\n\t\tnotes,\n\t\tevidence,\n\t\tcreatedAt: args.createdAt,\n\t\tupdatedAt: args.updatedAt,\n\t};\n}\n\nexport function setTaskSteps(state: TaskStepsState, inputs: readonly TaskStepInput[], now: string): TaskStepsState {\n\tif (inputs.length > MAX_TASK_STEPS) {\n\t\tthrow new TaskStepsError(`Task steps supports at most ${MAX_TASK_STEPS} steps.`);\n\t}\n\tconst existingByContent = new Map<string, TaskStep[]>();\n\tfor (const step of state.steps) {\n\t\tconst key = step.content.toLocaleLowerCase();\n\t\tconst matches = existingByContent.get(key) ?? [];\n\t\tmatches.push(step);\n\t\texistingByContent.set(key, matches);\n\t}\n\n\tlet nextStepNumber = state.nextStepNumber;\n\tconst steps = inputs.map((input) => {\n\t\tconst content = requireBoundedText(input.content, \"Task step content\", MAX_TASK_STEP_CONTENT_LENGTH);\n\t\tconst matches = existingByContent.get(content.toLocaleLowerCase());\n\t\tconst existing = matches?.shift();\n\t\tconst id = existing?.id ?? `step-${nextStepNumber++}`;\n\t\treturn createStep({\n\t\t\tinput: { ...input, content },\n\t\t\tid,\n\t\t\tcreatedAt: existing?.createdAt ?? now,\n\t\t\tupdatedAt: now,\n\t\t\texisting,\n\t\t});\n\t});\n\tconst activeIndex = steps.findLastIndex((step) => step.status === \"in_progress\");\n\tif (activeIndex >= 0) demoteOtherActiveSteps(steps, activeIndex);\n\treturn { ...nextState(state, steps, now), nextStepNumber };\n}\n\nexport function addTaskStep(state: TaskStepsState, input: TaskStepInput, now: string): TaskStepsState {\n\tif (state.steps.length >= MAX_TASK_STEPS) {\n\t\tthrow new TaskStepsError(`Task steps already has the maximum ${MAX_TASK_STEPS} steps.`);\n\t}\n\tconst step = createStep({ input, id: `step-${state.nextStepNumber}`, createdAt: now, updatedAt: now });\n\tconst steps = [...state.steps.map(cloneTaskStep), step];\n\tif (step.status === \"in_progress\") demoteOtherActiveSteps(steps, steps.length - 1);\n\treturn { ...nextState(state, steps, now), nextStepNumber: state.nextStepNumber + 1 };\n}\n\nexport function resolveTaskStepSelector(steps: readonly TaskStep[], selector: string): TaskStep {\n\tconst normalized = selector.trim().toLocaleLowerCase();\n\tif (!normalized) throw new TaskStepsError(\"Task step selector is required.\");\n\tif (normalized === \"current\" || normalized === \"active\") {\n\t\tconst active = steps.find((step) => step.status === \"in_progress\");\n\t\tif (!active) throw new TaskStepsError(\"No in_progress task step was found.\");\n\t\treturn active;\n\t}\n\n\tconst exactId = steps.find((step) => step.id.toLocaleLowerCase() === normalized);\n\tif (exactId) return exactId;\n\tconst idPrefix = steps.filter((step) => step.id.toLocaleLowerCase().startsWith(normalized));\n\tif (idPrefix.length === 1) return idPrefix[0];\n\tif (idPrefix.length > 1) {\n\t\tthrow new TaskStepsError(`Task step selector is ambiguous: ${idPrefix.map((step) => step.id).join(\", \")}.`);\n\t}\n\n\tconst exactContent = steps.filter((step) => step.content.toLocaleLowerCase() === normalized);\n\tif (exactContent.length === 1) return exactContent[0];\n\tconst contentMatches = steps.filter((step) => step.content.toLocaleLowerCase().includes(normalized));\n\tif (contentMatches.length === 1) return contentMatches[0];\n\tif (exactContent.length > 1 || contentMatches.length > 1) {\n\t\tconst matches = exactContent.length > 1 ? exactContent : contentMatches;\n\t\tthrow new TaskStepsError(`Task step selector is ambiguous: ${matches.map((step) => step.id).join(\", \")}.`);\n\t}\n\tthrow new TaskStepsError(`Task step not found for selector: ${selector}.`);\n}\n\nexport function updateTaskStep(\n\tstate: TaskStepsState,\n\tselector: string,\n\tupdate: TaskStepUpdate,\n\tnow: string,\n): TaskStepsState {\n\tconst selected = resolveTaskStepSelector(state.steps, selector);\n\tconst selectedIndex = state.steps.findIndex((step) => step.id === selected.id);\n\tconst steps = state.steps.map(cloneTaskStep);\n\tconst current = steps[selectedIndex];\n\tconst note = optionalBoundedText(update.note, \"Task step note\", MAX_TASK_STEP_NOTE_LENGTH);\n\tconst notes = note\n\t\t? appendUniqueStrings(current.notes, [note], \"Task step note\", MAX_TASK_STEP_NOTE_LENGTH)\n\t\t: [...current.notes];\n\tconst evidence = appendUniqueStrings(\n\t\tcurrent.evidence,\n\t\tupdate.evidence,\n\t\t\"Task step evidence\",\n\t\tMAX_TASK_STEP_EVIDENCE_LENGTH,\n\t);\n\tsteps[selectedIndex] = {\n\t\t...current,\n\t\tcontent:\n\t\t\tupdate.content === undefined\n\t\t\t\t? current.content\n\t\t\t\t: requireBoundedText(update.content, \"Task step content\", MAX_TASK_STEP_CONTENT_LENGTH),\n\t\tactiveForm:\n\t\t\tupdate.activeForm === undefined\n\t\t\t\t? current.activeForm\n\t\t\t\t: optionalBoundedText(update.activeForm, \"Task step active form\", MAX_TASK_STEP_CONTENT_LENGTH),\n\t\tstatus: update.status ?? current.status,\n\t\tpriority: update.priority ?? current.priority,\n\t\towner:\n\t\t\tupdate.owner === undefined\n\t\t\t\t? current.owner\n\t\t\t\t: optionalBoundedText(update.owner, \"Task step owner\", MAX_TASK_STEP_OWNER_LENGTH),\n\t\tnotes,\n\t\tevidence,\n\t\tupdatedAt: now,\n\t};\n\tif (steps[selectedIndex].status === \"in_progress\") demoteOtherActiveSteps(steps, selectedIndex);\n\treturn nextState(state, steps, now);\n}\n\nexport function clearTaskSteps(state: TaskStepsState, now: string): TaskStepsState {\n\treturn {\n\t\t...nextState(state, [], now),\n\t\tarchive: { completed: 0, cancelled: 0 },\n\t};\n}\n\nexport function compactTaskSteps(state: TaskStepsState, now: string): TaskStepsState {\n\tconst completed = state.steps.filter((step) => step.status === \"completed\").length;\n\tconst cancelled = state.steps.filter((step) => step.status === \"cancelled\").length;\n\tconst open = state.steps.filter((step) => step.status !== \"completed\" && step.status !== \"cancelled\");\n\treturn {\n\t\t...nextState(state, open, now),\n\t\tarchive: {\n\t\t\tcompleted: state.archive.completed + completed,\n\t\t\tcancelled: state.archive.cancelled + cancelled,\n\t\t\tcompactedAt: now,\n\t\t},\n\t};\n}\n\nexport function formatTaskSteps(\n\tstate: TaskStepsState,\n\toptions: { includeTerminal?: boolean; maxItems?: number } = {},\n): string {\n\tconst visible = options.includeTerminal\n\t\t? state.steps\n\t\t: state.steps.filter((step) => step.status !== \"completed\" && step.status !== \"cancelled\");\n\tconst maxItems = Math.max(1, Math.min(MAX_TASK_STEPS, Math.floor(options.maxItems ?? 20)));\n\tconst statusMarker: Record<TaskStepStatus, string> = {\n\t\tpending: \" \",\n\t\tin_progress: \">\",\n\t\tcompleted: \"x\",\n\t\tblocked: \"!\",\n\t\tcancelled: \"-\",\n\t};\n\tconst lines = [`Task steps (${visible.length} visible, ${state.steps.length} tracked):`];\n\tfor (const step of visible.slice(0, maxItems)) {\n\t\tconst details = [step.priority, step.owner].filter(Boolean).join(\", \");\n\t\tlines.push(\n\t\t\t`- [${statusMarker[step.status]}] ${step.id} ${step.activeForm || step.content}${details ? ` (${details})` : \"\"}`,\n\t\t);\n\t\tfor (const note of step.notes.slice(-2)) lines.push(` note: ${note}`);\n\t\tfor (const evidence of step.evidence.slice(-2)) lines.push(` evidence: ${evidence}`);\n\t}\n\tif (visible.length > maxItems) lines.push(`- … ${visible.length - maxItems} more`);\n\tif (state.archive.completed || state.archive.cancelled) {\n\t\tlines.push(\n\t\t\t`Archived terminal steps: ${state.archive.completed} completed, ${state.archive.cancelled} cancelled.`,\n\t\t);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nexport function formatTaskStepsContext(state: TaskStepsState, maxItems = 12): string | undefined {\n\tconst open = state.steps.filter((step) => step.status !== \"completed\" && step.status !== \"cancelled\");\n\tif (open.length === 0) return undefined;\n\tconst limit = Math.max(1, Math.min(MAX_TASK_STEPS, Math.floor(maxItems)));\n\tconst lines = [\n\t\t\"Current native task_steps context for this session:\",\n\t\t\"Open task_steps:\",\n\t\t...open.slice(0, limit).map((step) => `- [${step.status}] ${step.activeForm || step.content}`),\n\t];\n\tif (open.length > limit) lines.push(`- … ${open.length - limit} more open step(s)`);\n\tconst active = open.find((step) => step.status === \"in_progress\");\n\tlines.push(\n\t\t\"\",\n\t\tactive\n\t\t\t? `Continue the in_progress step first: ${active.activeForm || active.content}. Update it completed, blocked, or cancelled as soon as evidence is known.`\n\t\t\t: `No step is in_progress. Start the first open step before unrelated work: ${open[0].activeForm || open[0].content}.`,\n\t\t\"Use task_steps to keep this checklist current and leave no stale in_progress step before the final response.\",\n\t);\n\treturn lines.join(\"\\n\");\n}\n\nexport function serializeTaskStepsState(state: TaskStepsState): string {\n\treturn JSON.stringify(cloneTaskStepsState(state), null, 2);\n}\n\nexport function parseTaskStepsState(text: string): TaskStepsState | undefined {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(text);\n\t\treturn isTaskStepsState(parsed) ? cloneTaskStepsState(parsed) : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-selection-controller.d.ts","sourceRoot":"","sources":["../../../src/core/tool-selection/tool-selection-controller.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAEX,kBAAkB,EAClB,oBAAoB,EACpB,wBAAwB,EACxB,wBAAwB,EACxB,MAA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eAAe,CAAQ;IAE/B,YAAY,IAAI,EAAE,2BAA2B,EAE5C;IAED,SAAS,IAAI,IAAI,CAEhB;IAED,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,+BAA+B,CAqD1F;IAED,QAAQ,CAAC,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,GAAE,SAAS,OAAO,EAAO,GAAG,IAAI,CAavF;IAED,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,UAAU,GAAG,SAAS,GAAG,IAAI,CAIxE;IAED,OAAO,CAAC,iBAAiB;CAkBzB;AAED,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,cAAc,EAAE,CAAC","sourcesContent":["import {\n\tdecideExpectedUtility,\n\ttype ExpectedUtilityCandidate,\n\ttype ToolSelectionDecision,\n} from \"./expected-utility.ts\";\nimport type {\n\tToolExecutionObservation,\n\tToolPerformanceKey,\n\tToolPerformanceStore,\n\tToolSelectionIntentClass,\n\tToolSelectionObservation,\n} from \"./tool-performance-store.ts\";\n\nexport interface ToolSelectionTool {\n\tname: string;\n\tdescription?: string;\n\tparameters?: unknown;\n\tprofileAllowed?: boolean;\n\tcapabilityAllowed?: boolean;\n\tpathValidated?: boolean;\n\triskCost?: number;\n\tcontextCost?: number;\n}\n\nexport interface ToolSelectionControllerDeps {\n\tstore: ToolPerformanceStore;\n\tgetModelRef: () => string;\n\tgetActiveTools: () => readonly ToolSelectionTool[];\n\tisCandidateAllowed?: (toolName: string) => boolean;\n}\n\nexport interface ToolSelectionPendingObservation {\n\tid: string;\n\tkey: ToolPerformanceKey;\n\tfirstTool: boolean;\n\tstartedAt: number;\n\tinputTokenEstimate?: number;\n\tselection: Omit<ToolSelectionObservation, \"at\" | \"modelRef\" | \"intentClass\" | \"actualTool\" | \"succeeded\">;\n}\n\nconst INTENT_CLASSES: readonly ToolSelectionIntentClass[] = [\n\t\"read\",\n\t\"search\",\n\t\"execute\",\n\t\"write\",\n\t\"retrieve\",\n\t\"explain\",\n\t\"other\",\n];\n\nconst INTENT_WORDS: Record<ToolSelectionIntentClass, readonly string[]> = {\n\tread: [\"read\", \"cat\", \"ls\", \"list\", \"stat\", \"head\", \"tail\"],\n\tsearch: [\"search\", \"grep\", \"find\", \"glob\", \"ripgrep\", \"query\"],\n\texecute: [\"bash\", \"shell\", \"exec\", \"run\", \"process\", \"command\", \"script\"],\n\twrite: [\"write\", \"edit\", \"patch\", \"apply\", \"delete\", \"mkdir\", \"move\", \"rename\"],\n\tretrieve: [\"retrieve\", \"artifact\", \"recall\", \"memory\", \"fetch\", \"download\"],\n\texplain: [\"explain\", \"help\", \"describe\", \"inspect\", \"context\"],\n\tother: [],\n};\n\nfunction tokenize(value: string): string[] {\n\treturn value\n\t\t.toLowerCase()\n\t\t.split(/[^a-z0-9]+/u)\n\t\t.filter(Boolean);\n}\n\nfunction classifyToolIntent(tool: ToolSelectionTool): ToolSelectionIntentClass {\n\tconst tokens = tokenize(`${tool.name} ${tool.description ?? \"\"}`);\n\tlet best: ToolSelectionIntentClass = \"other\";\n\tlet bestScore = 0;\n\tfor (const intent of INTENT_CLASSES) {\n\t\tif (intent === \"other\") continue;\n\t\tconst score = INTENT_WORDS[intent].reduce((total, word) => total + (tokens.includes(word) ? 1 : 0), 0);\n\t\tif (score > bestScore) {\n\t\t\tbest = intent;\n\t\t\tbestScore = score;\n\t\t}\n\t}\n\treturn best;\n}\n\nfunction intentValue(intent: ToolSelectionIntentClass, toolIntent: ToolSelectionIntentClass): number {\n\tif (toolIntent === intent) return 0.85;\n\tif (intent === \"other\") return 0.35;\n\tif (toolIntent === \"other\") return 0.2;\n\treturn 0.12;\n}\n\nfunction noToolValue(intent: ToolSelectionIntentClass): number {\n\tswitch (intent) {\n\t\tcase \"explain\":\n\t\t\treturn 0.35;\n\t\tcase \"read\":\n\t\tcase \"search\":\n\t\tcase \"retrieve\":\n\t\t\treturn 0.12;\n\t\tcase \"write\":\n\t\tcase \"execute\":\n\t\t\treturn 0.05;\n\t\tdefault:\n\t\t\treturn 0.2;\n\t}\n}\n\nfunction estimateTokens(value: unknown): number | undefined {\n\ttry {\n\t\tconst serialized = typeof value === \"string\" ? value : JSON.stringify(value);\n\t\tif (!serialized) return undefined;\n\t\treturn Math.max(1, Math.ceil(serialized.length / 4));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction estimateContentTokens(content: readonly unknown[]): number | undefined {\n\tconst text = content\n\t\t.map((block) => {\n\t\t\tif (!block || typeof block !== \"object\") return \"\";\n\t\t\tconst candidate = block as { type?: unknown; text?: unknown };\n\t\t\treturn candidate.type === \"text\" && typeof candidate.text === \"string\" ? candidate.text : \"\";\n\t\t})\n\t\t.join(\"\\n\");\n\treturn estimateTokens(text);\n}\n\nfunction modelToolKey(modelRef: string, intentClass: ToolSelectionIntentClass, tool: string): ToolPerformanceKey {\n\treturn { modelRef, intentClass, tool };\n}\n\nfunction candidateFor(\n\tstore: ToolPerformanceStore,\n\tmodelRef: string,\n\tintentClass: ToolSelectionIntentClass,\n\ttool: ToolSelectionTool,\n\tactualTool: string,\n): ExpectedUtilityCandidate {\n\tconst key = modelToolKey(modelRef, intentClass, tool.name);\n\tconst stats = store.get(key);\n\treturn {\n\t\ttool: tool.name,\n\t\tvalue: intentValue(intentClass, classifyToolIntent(tool)),\n\t\talpha: stats.alpha,\n\t\tbeta: stats.beta,\n\t\tsampleCount: stats.sampleCount,\n\t\tlatencyMs: stats.latencyEwmaMs,\n\t\ttokenEstimate:\n\t\t\tstats.inputTokenEstimateEwma === undefined && stats.outputTokenEstimateEwma === undefined\n\t\t\t\t? undefined\n\t\t\t\t: (stats.inputTokenEstimateEwma ?? 0) + (stats.outputTokenEstimateEwma ?? 0),\n\t\triskCost: tool.riskCost,\n\t\tcontextCost: tool.contextCost,\n\t\tdeterministicMatch: tool.name === actualTool && tool.pathValidated !== false,\n\t\tautomaticEligible: tool.pathValidated !== false,\n\t};\n}\n\nexport class ToolSelectionController {\n\tprivate readonly deps: ToolSelectionControllerDeps;\n\tprivate readonly pending = new Map<string, ToolSelectionPendingObservation>();\n\tprivate firstToolInTurn = true;\n\n\tconstructor(deps: ToolSelectionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tstartTurn(): void {\n\t\tthis.firstToolInTurn = true;\n\t}\n\n\tbegin(toolCallId: string, toolName: string, args: unknown): ToolSelectionPendingObservation {\n\t\tconst modelRef = this.deps.getModelRef();\n\t\tconst activeTools = this.deps\n\t\t\t.getActiveTools()\n\t\t\t.filter(\n\t\t\t\t(tool) =>\n\t\t\t\t\ttool.profileAllowed !== false &&\n\t\t\t\t\ttool.capabilityAllowed !== false &&\n\t\t\t\t\t(this.deps.isCandidateAllowed?.(tool.name) ?? true),\n\t\t\t);\n\t\tconst actualTool = activeTools.find((tool) => tool.name === toolName) ?? {\n\t\t\tname: toolName,\n\t\t\tpathValidated: true,\n\t\t};\n\t\tconst intentClass = classifyToolIntent(actualTool);\n\t\tconst candidates = activeTools.map((tool) =>\n\t\t\tcandidateFor(\n\t\t\t\tthis.deps.store,\n\t\t\t\tmodelRef,\n\t\t\t\tintentClass,\n\t\t\t\ttool.name === toolName ? tool : { ...tool, pathValidated: false },\n\t\t\t\ttoolName,\n\t\t\t),\n\t\t);\n\t\tif (!candidates.some((candidate) => candidate.tool === toolName)) {\n\t\t\tcandidates.push(candidateFor(this.deps.store, modelRef, intentClass, actualTool, toolName));\n\t\t}\n\t\tcandidates.push({\n\t\t\ttool: \"no_tool\",\n\t\t\tvalue: noToolValue(intentClass),\n\t\t\talpha: 1,\n\t\t\tbeta: 1,\n\t\t\tsampleCount: 0,\n\t\t\tsuccessProbability: 1,\n\t\t\tlatencyMs: 0,\n\t\t\ttokenEstimate: 0,\n\t\t\triskCost: 0,\n\t\t\tcontextCost: 0,\n\t\t});\n\t\tconst decision = decideExpectedUtility(candidates);\n\t\tconst firstTool = this.firstToolInTurn;\n\t\tconst selection = this.selectionSnapshot(decision, firstTool);\n\t\tconst pending: ToolSelectionPendingObservation = {\n\t\t\tid: toolCallId,\n\t\t\tkey: modelToolKey(modelRef, intentClass, toolName),\n\t\t\tfirstTool: this.firstToolInTurn,\n\t\t\tstartedAt: Date.now(),\n\t\t\tinputTokenEstimate: estimateTokens(args),\n\t\t\tselection,\n\t\t};\n\t\tthis.firstToolInTurn = false;\n\t\tthis.pending.set(toolCallId, pending);\n\t\treturn pending;\n\t}\n\n\tcomplete(toolCallId: string, succeeded: boolean, content: readonly unknown[] = []): void {\n\t\tconst pending = this.pending.get(toolCallId);\n\t\tif (!pending) return;\n\t\tthis.pending.delete(toolCallId);\n\t\tconst execution: ToolExecutionObservation = {\n\t\t\tkey: pending.key,\n\t\t\tsuccess: succeeded,\n\t\t\tlatencyMs: Math.max(0, Date.now() - pending.startedAt),\n\t\t\tinputTokenEstimate: pending.inputTokenEstimate,\n\t\t\toutputTokenEstimate: estimateContentTokens(content),\n\t\t\tselection: pending.selection,\n\t\t};\n\t\tthis.deps.store.recordExecution(execution);\n\t}\n\n\trecordValidation(toolName: string, outcome: \"repaired\" | \"bounced\"): void {\n\t\tconst modelRef = this.deps.getModelRef();\n\t\tconst tool = this.deps.getActiveTools().find((candidate) => candidate.name === toolName) ?? { name: toolName };\n\t\tthis.deps.store.recordValidation(modelToolKey(modelRef, classifyToolIntent(tool), toolName), outcome);\n\t}\n\n\tprivate selectionSnapshot(\n\t\tdecision: ToolSelectionDecision,\n\t\tfirstTool: boolean,\n\t): ToolSelectionPendingObservation[\"selection\"] {\n\t\treturn {\n\t\t\tfirstTool,\n\t\t\tdisposition: decision.disposition,\n\t\t\trecommendation: decision.recommendation,\n\t\t\tshortlist: decision.shortlist,\n\t\t\tentropy: decision.entropy,\n\t\t\tmargin: decision.margin,\n\t\t\tranked: decision.ranked.map((candidate) => ({\n\t\t\t\ttool: candidate.tool,\n\t\t\t\tutility: candidate.utility,\n\t\t\t\tprobability: candidate.probability,\n\t\t\t})),\n\t\t};\n\t}\n}\n\nexport { classifyToolIntent, estimateContentTokens, estimateTokens };\n"]}
|
|
1
|
+
{"version":3,"file":"tool-selection-controller.d.ts","sourceRoot":"","sources":["../../../src/core/tool-selection/tool-selection-controller.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAEX,kBAAkB,EAClB,oBAAoB,EACpB,wBAAwB,EACxB,wBAAwB,EACxB,MAAM,6BAA6B,CAAC;AAErC,MAAM,WAAW,iBAAiB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,2BAA2B;IAC3C,KAAK,EAAE,oBAAoB,CAAC;IAC5B,WAAW,EAAE,MAAM,MAAM,CAAC;IAC1B,cAAc,EAAE,MAAM,SAAS,iBAAiB,EAAE,CAAC;IACnD,kBAAkB,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC;CACnD;AAED,MAAM,WAAW,+BAA+B;IAC/C,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,kBAAkB,CAAC;IACxB,SAAS,EAAE,OAAO,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,SAAS,EAAE,IAAI,CAAC,wBAAwB,EAAE,IAAI,GAAG,UAAU,GAAG,aAAa,GAAG,YAAY,GAAG,WAAW,CAAC,CAAC;CAC1G;AA6BD,iBAAS,kBAAkB,CAAC,IAAI,EAAE,iBAAiB,GAAG,wBAAwB,CAa7E;AAyBD,iBAAS,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAQ1D;AAED,iBAAS,qBAAqB,CAAC,OAAO,EAAE,SAAS,OAAO,EAAE,GAAG,MAAM,GAAG,SAAS,CAS9E;AAiCD,qBAAa,uBAAuB;IACnC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA8B;IACnD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAsD;IAC9E,OAAO,CAAC,eAAe,CAAQ;IAE/B,YAAY,IAAI,EAAE,2BAA2B,EAE5C;IAED,SAAS,IAAI,IAAI,CAEhB;IAED,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,+BAA+B,CAqD1F;IAED,QAAQ,CAAC,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,GAAE,SAAS,OAAO,EAAO,GAAG,IAAI,CAavF;IAED,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,UAAU,GAAG,SAAS,GAAG,IAAI,CAIxE;IAED,OAAO,CAAC,iBAAiB;CAkBzB;AAED,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,cAAc,EAAE,CAAC","sourcesContent":["import {\n\tdecideExpectedUtility,\n\ttype ExpectedUtilityCandidate,\n\ttype ToolSelectionDecision,\n} from \"./expected-utility.ts\";\nimport type {\n\tToolExecutionObservation,\n\tToolPerformanceKey,\n\tToolPerformanceStore,\n\tToolSelectionIntentClass,\n\tToolSelectionObservation,\n} from \"./tool-performance-store.ts\";\n\nexport interface ToolSelectionTool {\n\tname: string;\n\tdescription?: string;\n\tparameters?: unknown;\n\tprofileAllowed?: boolean;\n\tcapabilityAllowed?: boolean;\n\tpathValidated?: boolean;\n\triskCost?: number;\n\tcontextCost?: number;\n}\n\nexport interface ToolSelectionControllerDeps {\n\tstore: ToolPerformanceStore;\n\tgetModelRef: () => string;\n\tgetActiveTools: () => readonly ToolSelectionTool[];\n\tisCandidateAllowed?: (toolName: string) => boolean;\n}\n\nexport interface ToolSelectionPendingObservation {\n\tid: string;\n\tkey: ToolPerformanceKey;\n\tfirstTool: boolean;\n\tstartedAt: number;\n\tinputTokenEstimate?: number;\n\tselection: Omit<ToolSelectionObservation, \"at\" | \"modelRef\" | \"intentClass\" | \"actualTool\" | \"succeeded\">;\n}\n\nconst INTENT_CLASSES: readonly ToolSelectionIntentClass[] = [\n\t\"read\",\n\t\"search\",\n\t\"execute\",\n\t\"write\",\n\t\"retrieve\",\n\t\"explain\",\n\t\"other\",\n];\n\nconst INTENT_WORDS: Record<ToolSelectionIntentClass, readonly string[]> = {\n\tread: [\"read\", \"cat\", \"ls\", \"list\", \"stat\", \"head\", \"tail\"],\n\tsearch: [\"search\", \"grep\", \"find\", \"glob\", \"ripgrep\", \"query\"],\n\texecute: [\"bash\", \"python\", \"powershell\", \"shell\", \"exec\", \"run\", \"process\", \"command\", \"script\"],\n\twrite: [\"write\", \"edit\", \"patch\", \"apply\", \"delete\", \"mkdir\", \"move\", \"rename\"],\n\tretrieve: [\"retrieve\", \"artifact\", \"recall\", \"memory\", \"fetch\", \"download\"],\n\texplain: [\"explain\", \"help\", \"describe\", \"inspect\", \"context\"],\n\tother: [],\n};\n\nfunction tokenize(value: string): string[] {\n\treturn value\n\t\t.toLowerCase()\n\t\t.split(/[^a-z0-9]+/u)\n\t\t.filter(Boolean);\n}\n\nfunction classifyToolIntent(tool: ToolSelectionTool): ToolSelectionIntentClass {\n\tconst tokens = tokenize(`${tool.name} ${tool.description ?? \"\"}`);\n\tlet best: ToolSelectionIntentClass = \"other\";\n\tlet bestScore = 0;\n\tfor (const intent of INTENT_CLASSES) {\n\t\tif (intent === \"other\") continue;\n\t\tconst score = INTENT_WORDS[intent].reduce((total, word) => total + (tokens.includes(word) ? 1 : 0), 0);\n\t\tif (score > bestScore) {\n\t\t\tbest = intent;\n\t\t\tbestScore = score;\n\t\t}\n\t}\n\treturn best;\n}\n\nfunction intentValue(intent: ToolSelectionIntentClass, toolIntent: ToolSelectionIntentClass): number {\n\tif (toolIntent === intent) return 0.85;\n\tif (intent === \"other\") return 0.35;\n\tif (toolIntent === \"other\") return 0.2;\n\treturn 0.12;\n}\n\nfunction noToolValue(intent: ToolSelectionIntentClass): number {\n\tswitch (intent) {\n\t\tcase \"explain\":\n\t\t\treturn 0.35;\n\t\tcase \"read\":\n\t\tcase \"search\":\n\t\tcase \"retrieve\":\n\t\t\treturn 0.12;\n\t\tcase \"write\":\n\t\tcase \"execute\":\n\t\t\treturn 0.05;\n\t\tdefault:\n\t\t\treturn 0.2;\n\t}\n}\n\nfunction estimateTokens(value: unknown): number | undefined {\n\ttry {\n\t\tconst serialized = typeof value === \"string\" ? value : JSON.stringify(value);\n\t\tif (!serialized) return undefined;\n\t\treturn Math.max(1, Math.ceil(serialized.length / 4));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction estimateContentTokens(content: readonly unknown[]): number | undefined {\n\tconst text = content\n\t\t.map((block) => {\n\t\t\tif (!block || typeof block !== \"object\") return \"\";\n\t\t\tconst candidate = block as { type?: unknown; text?: unknown };\n\t\t\treturn candidate.type === \"text\" && typeof candidate.text === \"string\" ? candidate.text : \"\";\n\t\t})\n\t\t.join(\"\\n\");\n\treturn estimateTokens(text);\n}\n\nfunction modelToolKey(modelRef: string, intentClass: ToolSelectionIntentClass, tool: string): ToolPerformanceKey {\n\treturn { modelRef, intentClass, tool };\n}\n\nfunction candidateFor(\n\tstore: ToolPerformanceStore,\n\tmodelRef: string,\n\tintentClass: ToolSelectionIntentClass,\n\ttool: ToolSelectionTool,\n\tactualTool: string,\n): ExpectedUtilityCandidate {\n\tconst key = modelToolKey(modelRef, intentClass, tool.name);\n\tconst stats = store.get(key);\n\treturn {\n\t\ttool: tool.name,\n\t\tvalue: intentValue(intentClass, classifyToolIntent(tool)),\n\t\talpha: stats.alpha,\n\t\tbeta: stats.beta,\n\t\tsampleCount: stats.sampleCount,\n\t\tlatencyMs: stats.latencyEwmaMs,\n\t\ttokenEstimate:\n\t\t\tstats.inputTokenEstimateEwma === undefined && stats.outputTokenEstimateEwma === undefined\n\t\t\t\t? undefined\n\t\t\t\t: (stats.inputTokenEstimateEwma ?? 0) + (stats.outputTokenEstimateEwma ?? 0),\n\t\triskCost: tool.riskCost,\n\t\tcontextCost: tool.contextCost,\n\t\tdeterministicMatch: tool.name === actualTool && tool.pathValidated !== false,\n\t\tautomaticEligible: tool.pathValidated !== false,\n\t};\n}\n\nexport class ToolSelectionController {\n\tprivate readonly deps: ToolSelectionControllerDeps;\n\tprivate readonly pending = new Map<string, ToolSelectionPendingObservation>();\n\tprivate firstToolInTurn = true;\n\n\tconstructor(deps: ToolSelectionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tstartTurn(): void {\n\t\tthis.firstToolInTurn = true;\n\t}\n\n\tbegin(toolCallId: string, toolName: string, args: unknown): ToolSelectionPendingObservation {\n\t\tconst modelRef = this.deps.getModelRef();\n\t\tconst activeTools = this.deps\n\t\t\t.getActiveTools()\n\t\t\t.filter(\n\t\t\t\t(tool) =>\n\t\t\t\t\ttool.profileAllowed !== false &&\n\t\t\t\t\ttool.capabilityAllowed !== false &&\n\t\t\t\t\t(this.deps.isCandidateAllowed?.(tool.name) ?? true),\n\t\t\t);\n\t\tconst actualTool = activeTools.find((tool) => tool.name === toolName) ?? {\n\t\t\tname: toolName,\n\t\t\tpathValidated: true,\n\t\t};\n\t\tconst intentClass = classifyToolIntent(actualTool);\n\t\tconst candidates = activeTools.map((tool) =>\n\t\t\tcandidateFor(\n\t\t\t\tthis.deps.store,\n\t\t\t\tmodelRef,\n\t\t\t\tintentClass,\n\t\t\t\ttool.name === toolName ? tool : { ...tool, pathValidated: false },\n\t\t\t\ttoolName,\n\t\t\t),\n\t\t);\n\t\tif (!candidates.some((candidate) => candidate.tool === toolName)) {\n\t\t\tcandidates.push(candidateFor(this.deps.store, modelRef, intentClass, actualTool, toolName));\n\t\t}\n\t\tcandidates.push({\n\t\t\ttool: \"no_tool\",\n\t\t\tvalue: noToolValue(intentClass),\n\t\t\talpha: 1,\n\t\t\tbeta: 1,\n\t\t\tsampleCount: 0,\n\t\t\tsuccessProbability: 1,\n\t\t\tlatencyMs: 0,\n\t\t\ttokenEstimate: 0,\n\t\t\triskCost: 0,\n\t\t\tcontextCost: 0,\n\t\t});\n\t\tconst decision = decideExpectedUtility(candidates);\n\t\tconst firstTool = this.firstToolInTurn;\n\t\tconst selection = this.selectionSnapshot(decision, firstTool);\n\t\tconst pending: ToolSelectionPendingObservation = {\n\t\t\tid: toolCallId,\n\t\t\tkey: modelToolKey(modelRef, intentClass, toolName),\n\t\t\tfirstTool: this.firstToolInTurn,\n\t\t\tstartedAt: Date.now(),\n\t\t\tinputTokenEstimate: estimateTokens(args),\n\t\t\tselection,\n\t\t};\n\t\tthis.firstToolInTurn = false;\n\t\tthis.pending.set(toolCallId, pending);\n\t\treturn pending;\n\t}\n\n\tcomplete(toolCallId: string, succeeded: boolean, content: readonly unknown[] = []): void {\n\t\tconst pending = this.pending.get(toolCallId);\n\t\tif (!pending) return;\n\t\tthis.pending.delete(toolCallId);\n\t\tconst execution: ToolExecutionObservation = {\n\t\t\tkey: pending.key,\n\t\t\tsuccess: succeeded,\n\t\t\tlatencyMs: Math.max(0, Date.now() - pending.startedAt),\n\t\t\tinputTokenEstimate: pending.inputTokenEstimate,\n\t\t\toutputTokenEstimate: estimateContentTokens(content),\n\t\t\tselection: pending.selection,\n\t\t};\n\t\tthis.deps.store.recordExecution(execution);\n\t}\n\n\trecordValidation(toolName: string, outcome: \"repaired\" | \"bounced\"): void {\n\t\tconst modelRef = this.deps.getModelRef();\n\t\tconst tool = this.deps.getActiveTools().find((candidate) => candidate.name === toolName) ?? { name: toolName };\n\t\tthis.deps.store.recordValidation(modelToolKey(modelRef, classifyToolIntent(tool), toolName), outcome);\n\t}\n\n\tprivate selectionSnapshot(\n\t\tdecision: ToolSelectionDecision,\n\t\tfirstTool: boolean,\n\t): ToolSelectionPendingObservation[\"selection\"] {\n\t\treturn {\n\t\t\tfirstTool,\n\t\t\tdisposition: decision.disposition,\n\t\t\trecommendation: decision.recommendation,\n\t\t\tshortlist: decision.shortlist,\n\t\t\tentropy: decision.entropy,\n\t\t\tmargin: decision.margin,\n\t\t\tranked: decision.ranked.map((candidate) => ({\n\t\t\t\ttool: candidate.tool,\n\t\t\t\tutility: candidate.utility,\n\t\t\t\tprobability: candidate.probability,\n\t\t\t})),\n\t\t};\n\t}\n}\n\nexport { classifyToolIntent, estimateContentTokens, estimateTokens };\n"]}
|
|
@@ -11,7 +11,7 @@ const INTENT_CLASSES = [
|
|
|
11
11
|
const INTENT_WORDS = {
|
|
12
12
|
read: ["read", "cat", "ls", "list", "stat", "head", "tail"],
|
|
13
13
|
search: ["search", "grep", "find", "glob", "ripgrep", "query"],
|
|
14
|
-
execute: ["bash", "shell", "exec", "run", "process", "command", "script"],
|
|
14
|
+
execute: ["bash", "python", "powershell", "shell", "exec", "run", "process", "command", "script"],
|
|
15
15
|
write: ["write", "edit", "patch", "apply", "delete", "mkdir", "move", "rename"],
|
|
16
16
|
retrieve: ["retrieve", "artifact", "recall", "memory", "fetch", "download"],
|
|
17
17
|
explain: ["explain", "help", "describe", "inspect", "context"],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-selection-controller.js","sourceRoot":"","sources":["../../../src/core/tool-selection/tool-selection-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,qBAAqB,GAGrB,MAAM,uBAAuB,CAAC;AAoC/B,MAAM,cAAc,GAAwC;IAC3D,MAAM;IACN,QAAQ;IACR,SAAS;IACT,OAAO;IACP,UAAU;IACV,SAAS;IACT,OAAO;CACP,CAAC;AAEF,MAAM,YAAY,GAAwD;IACzE,IAAI,EAAE,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC;IAC3D,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM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C,gBAAgB,CAAC,YAAY,CAAC,QAAQ,EAAE,kBAAkB,CAAC,IAAI,CAAC,EAAE,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAC;IAAA,CACtG;IAEO,iBAAiB,CACxB,QAA+B,EAC/B,SAAkB,EAC6B;QAC/C,OAAO;YACN,SAAS;YACT,WAAW,EAAE,QAAQ,CAAC,WAAW;YACjC,cAAc,EAAE,QAAQ,CAAC,cAAc;YACvC,SAAS,EAAE,QAAQ,CAAC,SAAS;YAC7B,OAAO,EAAE,QAAQ,CAAC,OAAO;YACzB,MAAM,EAAE,QAAQ,CAAC,MAAM;YACvB,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;gBAC3C,IAAI,EAAE,SAAS,CAAC,IAAI;gBACpB,OAAO,EAAE,SAAS,CAAC,OAAO;gBAC1B,WAAW,EAAE,SAAS,CAAC,WAAW;aAClC,CAAC,CAAC;SACH,CAAC;IAAA,CACF;CACD;AAED,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,cAAc,EAAE,CAAC","sourcesContent":["import {\n\tdecideExpectedUtility,\n\ttype ExpectedUtilityCandidate,\n\ttype ToolSelectionDecision,\n} from \"./expected-utility.ts\";\nimport type {\n\tToolExecutionObservation,\n\tToolPerformanceKey,\n\tToolPerformanceStore,\n\tToolSelectionIntentClass,\n\tToolSelectionObservation,\n} from \"./tool-performance-store.ts\";\n\nexport interface ToolSelectionTool {\n\tname: string;\n\tdescription?: string;\n\tparameters?: unknown;\n\tprofileAllowed?: boolean;\n\tcapabilityAllowed?: boolean;\n\tpathValidated?: boolean;\n\triskCost?: number;\n\tcontextCost?: number;\n}\n\nexport interface ToolSelectionControllerDeps {\n\tstore: ToolPerformanceStore;\n\tgetModelRef: () => string;\n\tgetActiveTools: () => readonly ToolSelectionTool[];\n\tisCandidateAllowed?: (toolName: string) => boolean;\n}\n\nexport interface ToolSelectionPendingObservation {\n\tid: string;\n\tkey: ToolPerformanceKey;\n\tfirstTool: boolean;\n\tstartedAt: number;\n\tinputTokenEstimate?: number;\n\tselection: Omit<ToolSelectionObservation, \"at\" | \"modelRef\" | \"intentClass\" | \"actualTool\" | \"succeeded\">;\n}\n\nconst INTENT_CLASSES: readonly ToolSelectionIntentClass[] = [\n\t\"read\",\n\t\"search\",\n\t\"execute\",\n\t\"write\",\n\t\"retrieve\",\n\t\"explain\",\n\t\"other\",\n];\n\nconst INTENT_WORDS: Record<ToolSelectionIntentClass, readonly string[]> = {\n\tread: [\"read\", \"cat\", \"ls\", \"list\", \"stat\", \"head\", \"tail\"],\n\tsearch: [\"search\", \"grep\", \"find\", \"glob\", \"ripgrep\", \"query\"],\n\texecute: [\"bash\", \"shell\", \"exec\", \"run\", \"process\", \"command\", \"script\"],\n\twrite: [\"write\", \"edit\", \"patch\", \"apply\", \"delete\", \"mkdir\", \"move\", \"rename\"],\n\tretrieve: [\"retrieve\", \"artifact\", \"recall\", \"memory\", \"fetch\", \"download\"],\n\texplain: [\"explain\", \"help\", \"describe\", \"inspect\", \"context\"],\n\tother: [],\n};\n\nfunction tokenize(value: string): string[] {\n\treturn value\n\t\t.toLowerCase()\n\t\t.split(/[^a-z0-9]+/u)\n\t\t.filter(Boolean);\n}\n\nfunction classifyToolIntent(tool: ToolSelectionTool): ToolSelectionIntentClass {\n\tconst tokens = tokenize(`${tool.name} ${tool.description ?? \"\"}`);\n\tlet best: ToolSelectionIntentClass = \"other\";\n\tlet bestScore = 0;\n\tfor (const intent of INTENT_CLASSES) {\n\t\tif (intent === \"other\") continue;\n\t\tconst score = INTENT_WORDS[intent].reduce((total, word) => total + (tokens.includes(word) ? 1 : 0), 0);\n\t\tif (score > bestScore) {\n\t\t\tbest = intent;\n\t\t\tbestScore = score;\n\t\t}\n\t}\n\treturn best;\n}\n\nfunction intentValue(intent: ToolSelectionIntentClass, toolIntent: ToolSelectionIntentClass): number {\n\tif (toolIntent === intent) return 0.85;\n\tif (intent === \"other\") return 0.35;\n\tif (toolIntent === \"other\") return 0.2;\n\treturn 0.12;\n}\n\nfunction noToolValue(intent: ToolSelectionIntentClass): number {\n\tswitch (intent) {\n\t\tcase \"explain\":\n\t\t\treturn 0.35;\n\t\tcase \"read\":\n\t\tcase \"search\":\n\t\tcase \"retrieve\":\n\t\t\treturn 0.12;\n\t\tcase \"write\":\n\t\tcase \"execute\":\n\t\t\treturn 0.05;\n\t\tdefault:\n\t\t\treturn 0.2;\n\t}\n}\n\nfunction estimateTokens(value: unknown): number | undefined {\n\ttry {\n\t\tconst serialized = typeof value === \"string\" ? value : JSON.stringify(value);\n\t\tif (!serialized) return undefined;\n\t\treturn Math.max(1, Math.ceil(serialized.length / 4));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction estimateContentTokens(content: readonly unknown[]): number | undefined {\n\tconst text = content\n\t\t.map((block) => {\n\t\t\tif (!block || typeof block !== \"object\") return \"\";\n\t\t\tconst candidate = block as { type?: unknown; text?: unknown };\n\t\t\treturn candidate.type === \"text\" && typeof candidate.text === \"string\" ? candidate.text : \"\";\n\t\t})\n\t\t.join(\"\\n\");\n\treturn estimateTokens(text);\n}\n\nfunction modelToolKey(modelRef: string, intentClass: ToolSelectionIntentClass, tool: string): ToolPerformanceKey {\n\treturn { modelRef, intentClass, tool };\n}\n\nfunction candidateFor(\n\tstore: ToolPerformanceStore,\n\tmodelRef: string,\n\tintentClass: ToolSelectionIntentClass,\n\ttool: ToolSelectionTool,\n\tactualTool: string,\n): ExpectedUtilityCandidate {\n\tconst key = modelToolKey(modelRef, intentClass, tool.name);\n\tconst stats = store.get(key);\n\treturn {\n\t\ttool: tool.name,\n\t\tvalue: intentValue(intentClass, classifyToolIntent(tool)),\n\t\talpha: stats.alpha,\n\t\tbeta: stats.beta,\n\t\tsampleCount: stats.sampleCount,\n\t\tlatencyMs: stats.latencyEwmaMs,\n\t\ttokenEstimate:\n\t\t\tstats.inputTokenEstimateEwma === undefined && stats.outputTokenEstimateEwma === undefined\n\t\t\t\t? undefined\n\t\t\t\t: (stats.inputTokenEstimateEwma ?? 0) + (stats.outputTokenEstimateEwma ?? 0),\n\t\triskCost: tool.riskCost,\n\t\tcontextCost: tool.contextCost,\n\t\tdeterministicMatch: tool.name === actualTool && tool.pathValidated !== false,\n\t\tautomaticEligible: tool.pathValidated !== false,\n\t};\n}\n\nexport class ToolSelectionController {\n\tprivate readonly deps: ToolSelectionControllerDeps;\n\tprivate readonly pending = new Map<string, ToolSelectionPendingObservation>();\n\tprivate firstToolInTurn = true;\n\n\tconstructor(deps: ToolSelectionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tstartTurn(): void {\n\t\tthis.firstToolInTurn = true;\n\t}\n\n\tbegin(toolCallId: string, toolName: string, args: unknown): ToolSelectionPendingObservation {\n\t\tconst modelRef = this.deps.getModelRef();\n\t\tconst activeTools = this.deps\n\t\t\t.getActiveTools()\n\t\t\t.filter(\n\t\t\t\t(tool) =>\n\t\t\t\t\ttool.profileAllowed !== false &&\n\t\t\t\t\ttool.capabilityAllowed !== false &&\n\t\t\t\t\t(this.deps.isCandidateAllowed?.(tool.name) ?? true),\n\t\t\t);\n\t\tconst actualTool = activeTools.find((tool) => tool.name === toolName) ?? {\n\t\t\tname: toolName,\n\t\t\tpathValidated: true,\n\t\t};\n\t\tconst intentClass = classifyToolIntent(actualTool);\n\t\tconst candidates = activeTools.map((tool) =>\n\t\t\tcandidateFor(\n\t\t\t\tthis.deps.store,\n\t\t\t\tmodelRef,\n\t\t\t\tintentClass,\n\t\t\t\ttool.name === toolName ? tool : { ...tool, pathValidated: false },\n\t\t\t\ttoolName,\n\t\t\t),\n\t\t);\n\t\tif (!candidates.some((candidate) => candidate.tool === toolName)) {\n\t\t\tcandidates.push(candidateFor(this.deps.store, modelRef, intentClass, actualTool, toolName));\n\t\t}\n\t\tcandidates.push({\n\t\t\ttool: \"no_tool\",\n\t\t\tvalue: noToolValue(intentClass),\n\t\t\talpha: 1,\n\t\t\tbeta: 1,\n\t\t\tsampleCount: 0,\n\t\t\tsuccessProbability: 1,\n\t\t\tlatencyMs: 0,\n\t\t\ttokenEstimate: 0,\n\t\t\triskCost: 0,\n\t\t\tcontextCost: 0,\n\t\t});\n\t\tconst decision = decideExpectedUtility(candidates);\n\t\tconst firstTool = this.firstToolInTurn;\n\t\tconst selection = this.selectionSnapshot(decision, firstTool);\n\t\tconst pending: ToolSelectionPendingObservation = {\n\t\t\tid: toolCallId,\n\t\t\tkey: modelToolKey(modelRef, intentClass, toolName),\n\t\t\tfirstTool: this.firstToolInTurn,\n\t\t\tstartedAt: Date.now(),\n\t\t\tinputTokenEstimate: estimateTokens(args),\n\t\t\tselection,\n\t\t};\n\t\tthis.firstToolInTurn = false;\n\t\tthis.pending.set(toolCallId, pending);\n\t\treturn pending;\n\t}\n\n\tcomplete(toolCallId: string, succeeded: boolean, content: readonly unknown[] = []): void {\n\t\tconst pending = this.pending.get(toolCallId);\n\t\tif (!pending) return;\n\t\tthis.pending.delete(toolCallId);\n\t\tconst execution: ToolExecutionObservation = {\n\t\t\tkey: pending.key,\n\t\t\tsuccess: succeeded,\n\t\t\tlatencyMs: Math.max(0, Date.now() - pending.startedAt),\n\t\t\tinputTokenEstimate: pending.inputTokenEstimate,\n\t\t\toutputTokenEstimate: estimateContentTokens(content),\n\t\t\tselection: pending.selection,\n\t\t};\n\t\tthis.deps.store.recordExecution(execution);\n\t}\n\n\trecordValidation(toolName: string, outcome: \"repaired\" | \"bounced\"): void {\n\t\tconst modelRef = this.deps.getModelRef();\n\t\tconst tool = this.deps.getActiveTools().find((candidate) => candidate.name === toolName) ?? { name: toolName };\n\t\tthis.deps.store.recordValidation(modelToolKey(modelRef, classifyToolIntent(tool), toolName), outcome);\n\t}\n\n\tprivate selectionSnapshot(\n\t\tdecision: ToolSelectionDecision,\n\t\tfirstTool: boolean,\n\t): ToolSelectionPendingObservation[\"selection\"] {\n\t\treturn {\n\t\t\tfirstTool,\n\t\t\tdisposition: decision.disposition,\n\t\t\trecommendation: decision.recommendation,\n\t\t\tshortlist: decision.shortlist,\n\t\t\tentropy: decision.entropy,\n\t\t\tmargin: decision.margin,\n\t\t\tranked: decision.ranked.map((candidate) => ({\n\t\t\t\ttool: candidate.tool,\n\t\t\t\tutility: candidate.utility,\n\t\t\t\tprobability: candidate.probability,\n\t\t\t})),\n\t\t};\n\t}\n}\n\nexport { classifyToolIntent, estimateContentTokens, estimateTokens };\n"]}
|
|
1
|
+
{"version":3,"file":"tool-selection-controller.js","sourceRoot":"","sources":["../../../src/core/tool-selection/tool-selection-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,qBAAqB,GAGrB,MAAM,uBAAuB,CAAC;AAoC/B,MAAM,cAAc,GAAwC;IAC3D,MAAM;IACN,QAAQ;IACR,SAAS;IACT,OAAO;IACP,UAAU;IACV,SAAS;IACT,OAAO;CACP,CAAC;AAEF,MAAM,YAAY,GAAwD;IACzE,IAAI,EAAE,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC;IAC3D,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,CAAC;IAC9D,OAAO,EAAE,CAAC,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,CAAC;IACjG,KAAK,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC;IAC/E,QAAQ,EAAE,CAAC,UAAU,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,CAAC;IAC3E,OAAO,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,CAAC;IAC9D,KAAK,EA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AAE,SAAS,CAAC,IAAI;gBACpB,OAAO,EAAE,SAAS,CAAC,OAAO;gBAC1B,WAAW,EAAE,SAAS,CAAC,WAAW;aAClC,CAAC,CAAC;SACH,CAAC;IAAA,CACF;CACD;AAED,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,cAAc,EAAE,CAAC","sourcesContent":["import {\n\tdecideExpectedUtility,\n\ttype ExpectedUtilityCandidate,\n\ttype ToolSelectionDecision,\n} from \"./expected-utility.ts\";\nimport type {\n\tToolExecutionObservation,\n\tToolPerformanceKey,\n\tToolPerformanceStore,\n\tToolSelectionIntentClass,\n\tToolSelectionObservation,\n} from \"./tool-performance-store.ts\";\n\nexport interface ToolSelectionTool {\n\tname: string;\n\tdescription?: string;\n\tparameters?: unknown;\n\tprofileAllowed?: boolean;\n\tcapabilityAllowed?: boolean;\n\tpathValidated?: boolean;\n\triskCost?: number;\n\tcontextCost?: number;\n}\n\nexport interface ToolSelectionControllerDeps {\n\tstore: ToolPerformanceStore;\n\tgetModelRef: () => string;\n\tgetActiveTools: () => readonly ToolSelectionTool[];\n\tisCandidateAllowed?: (toolName: string) => boolean;\n}\n\nexport interface ToolSelectionPendingObservation {\n\tid: string;\n\tkey: ToolPerformanceKey;\n\tfirstTool: boolean;\n\tstartedAt: number;\n\tinputTokenEstimate?: number;\n\tselection: Omit<ToolSelectionObservation, \"at\" | \"modelRef\" | \"intentClass\" | \"actualTool\" | \"succeeded\">;\n}\n\nconst INTENT_CLASSES: readonly ToolSelectionIntentClass[] = [\n\t\"read\",\n\t\"search\",\n\t\"execute\",\n\t\"write\",\n\t\"retrieve\",\n\t\"explain\",\n\t\"other\",\n];\n\nconst INTENT_WORDS: Record<ToolSelectionIntentClass, readonly string[]> = {\n\tread: [\"read\", \"cat\", \"ls\", \"list\", \"stat\", \"head\", \"tail\"],\n\tsearch: [\"search\", \"grep\", \"find\", \"glob\", \"ripgrep\", \"query\"],\n\texecute: [\"bash\", \"python\", \"powershell\", \"shell\", \"exec\", \"run\", \"process\", \"command\", \"script\"],\n\twrite: [\"write\", \"edit\", \"patch\", \"apply\", \"delete\", \"mkdir\", \"move\", \"rename\"],\n\tretrieve: [\"retrieve\", \"artifact\", \"recall\", \"memory\", \"fetch\", \"download\"],\n\texplain: [\"explain\", \"help\", \"describe\", \"inspect\", \"context\"],\n\tother: [],\n};\n\nfunction tokenize(value: string): string[] {\n\treturn value\n\t\t.toLowerCase()\n\t\t.split(/[^a-z0-9]+/u)\n\t\t.filter(Boolean);\n}\n\nfunction classifyToolIntent(tool: ToolSelectionTool): ToolSelectionIntentClass {\n\tconst tokens = tokenize(`${tool.name} ${tool.description ?? \"\"}`);\n\tlet best: ToolSelectionIntentClass = \"other\";\n\tlet bestScore = 0;\n\tfor (const intent of INTENT_CLASSES) {\n\t\tif (intent === \"other\") continue;\n\t\tconst score = INTENT_WORDS[intent].reduce((total, word) => total + (tokens.includes(word) ? 1 : 0), 0);\n\t\tif (score > bestScore) {\n\t\t\tbest = intent;\n\t\t\tbestScore = score;\n\t\t}\n\t}\n\treturn best;\n}\n\nfunction intentValue(intent: ToolSelectionIntentClass, toolIntent: ToolSelectionIntentClass): number {\n\tif (toolIntent === intent) return 0.85;\n\tif (intent === \"other\") return 0.35;\n\tif (toolIntent === \"other\") return 0.2;\n\treturn 0.12;\n}\n\nfunction noToolValue(intent: ToolSelectionIntentClass): number {\n\tswitch (intent) {\n\t\tcase \"explain\":\n\t\t\treturn 0.35;\n\t\tcase \"read\":\n\t\tcase \"search\":\n\t\tcase \"retrieve\":\n\t\t\treturn 0.12;\n\t\tcase \"write\":\n\t\tcase \"execute\":\n\t\t\treturn 0.05;\n\t\tdefault:\n\t\t\treturn 0.2;\n\t}\n}\n\nfunction estimateTokens(value: unknown): number | undefined {\n\ttry {\n\t\tconst serialized = typeof value === \"string\" ? value : JSON.stringify(value);\n\t\tif (!serialized) return undefined;\n\t\treturn Math.max(1, Math.ceil(serialized.length / 4));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction estimateContentTokens(content: readonly unknown[]): number | undefined {\n\tconst text = content\n\t\t.map((block) => {\n\t\t\tif (!block || typeof block !== \"object\") return \"\";\n\t\t\tconst candidate = block as { type?: unknown; text?: unknown };\n\t\t\treturn candidate.type === \"text\" && typeof candidate.text === \"string\" ? candidate.text : \"\";\n\t\t})\n\t\t.join(\"\\n\");\n\treturn estimateTokens(text);\n}\n\nfunction modelToolKey(modelRef: string, intentClass: ToolSelectionIntentClass, tool: string): ToolPerformanceKey {\n\treturn { modelRef, intentClass, tool };\n}\n\nfunction candidateFor(\n\tstore: ToolPerformanceStore,\n\tmodelRef: string,\n\tintentClass: ToolSelectionIntentClass,\n\ttool: ToolSelectionTool,\n\tactualTool: string,\n): ExpectedUtilityCandidate {\n\tconst key = modelToolKey(modelRef, intentClass, tool.name);\n\tconst stats = store.get(key);\n\treturn {\n\t\ttool: tool.name,\n\t\tvalue: intentValue(intentClass, classifyToolIntent(tool)),\n\t\talpha: stats.alpha,\n\t\tbeta: stats.beta,\n\t\tsampleCount: stats.sampleCount,\n\t\tlatencyMs: stats.latencyEwmaMs,\n\t\ttokenEstimate:\n\t\t\tstats.inputTokenEstimateEwma === undefined && stats.outputTokenEstimateEwma === undefined\n\t\t\t\t? undefined\n\t\t\t\t: (stats.inputTokenEstimateEwma ?? 0) + (stats.outputTokenEstimateEwma ?? 0),\n\t\triskCost: tool.riskCost,\n\t\tcontextCost: tool.contextCost,\n\t\tdeterministicMatch: tool.name === actualTool && tool.pathValidated !== false,\n\t\tautomaticEligible: tool.pathValidated !== false,\n\t};\n}\n\nexport class ToolSelectionController {\n\tprivate readonly deps: ToolSelectionControllerDeps;\n\tprivate readonly pending = new Map<string, ToolSelectionPendingObservation>();\n\tprivate firstToolInTurn = true;\n\n\tconstructor(deps: ToolSelectionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tstartTurn(): void {\n\t\tthis.firstToolInTurn = true;\n\t}\n\n\tbegin(toolCallId: string, toolName: string, args: unknown): ToolSelectionPendingObservation {\n\t\tconst modelRef = this.deps.getModelRef();\n\t\tconst activeTools = this.deps\n\t\t\t.getActiveTools()\n\t\t\t.filter(\n\t\t\t\t(tool) =>\n\t\t\t\t\ttool.profileAllowed !== false &&\n\t\t\t\t\ttool.capabilityAllowed !== false &&\n\t\t\t\t\t(this.deps.isCandidateAllowed?.(tool.name) ?? true),\n\t\t\t);\n\t\tconst actualTool = activeTools.find((tool) => tool.name === toolName) ?? {\n\t\t\tname: toolName,\n\t\t\tpathValidated: true,\n\t\t};\n\t\tconst intentClass = classifyToolIntent(actualTool);\n\t\tconst candidates = activeTools.map((tool) =>\n\t\t\tcandidateFor(\n\t\t\t\tthis.deps.store,\n\t\t\t\tmodelRef,\n\t\t\t\tintentClass,\n\t\t\t\ttool.name === toolName ? tool : { ...tool, pathValidated: false },\n\t\t\t\ttoolName,\n\t\t\t),\n\t\t);\n\t\tif (!candidates.some((candidate) => candidate.tool === toolName)) {\n\t\t\tcandidates.push(candidateFor(this.deps.store, modelRef, intentClass, actualTool, toolName));\n\t\t}\n\t\tcandidates.push({\n\t\t\ttool: \"no_tool\",\n\t\t\tvalue: noToolValue(intentClass),\n\t\t\talpha: 1,\n\t\t\tbeta: 1,\n\t\t\tsampleCount: 0,\n\t\t\tsuccessProbability: 1,\n\t\t\tlatencyMs: 0,\n\t\t\ttokenEstimate: 0,\n\t\t\triskCost: 0,\n\t\t\tcontextCost: 0,\n\t\t});\n\t\tconst decision = decideExpectedUtility(candidates);\n\t\tconst firstTool = this.firstToolInTurn;\n\t\tconst selection = this.selectionSnapshot(decision, firstTool);\n\t\tconst pending: ToolSelectionPendingObservation = {\n\t\t\tid: toolCallId,\n\t\t\tkey: modelToolKey(modelRef, intentClass, toolName),\n\t\t\tfirstTool: this.firstToolInTurn,\n\t\t\tstartedAt: Date.now(),\n\t\t\tinputTokenEstimate: estimateTokens(args),\n\t\t\tselection,\n\t\t};\n\t\tthis.firstToolInTurn = false;\n\t\tthis.pending.set(toolCallId, pending);\n\t\treturn pending;\n\t}\n\n\tcomplete(toolCallId: string, succeeded: boolean, content: readonly unknown[] = []): void {\n\t\tconst pending = this.pending.get(toolCallId);\n\t\tif (!pending) return;\n\t\tthis.pending.delete(toolCallId);\n\t\tconst execution: ToolExecutionObservation = {\n\t\t\tkey: pending.key,\n\t\t\tsuccess: succeeded,\n\t\t\tlatencyMs: Math.max(0, Date.now() - pending.startedAt),\n\t\t\tinputTokenEstimate: pending.inputTokenEstimate,\n\t\t\toutputTokenEstimate: estimateContentTokens(content),\n\t\t\tselection: pending.selection,\n\t\t};\n\t\tthis.deps.store.recordExecution(execution);\n\t}\n\n\trecordValidation(toolName: string, outcome: \"repaired\" | \"bounced\"): void {\n\t\tconst modelRef = this.deps.getModelRef();\n\t\tconst tool = this.deps.getActiveTools().find((candidate) => candidate.name === toolName) ?? { name: toolName };\n\t\tthis.deps.store.recordValidation(modelToolKey(modelRef, classifyToolIntent(tool), toolName), outcome);\n\t}\n\n\tprivate selectionSnapshot(\n\t\tdecision: ToolSelectionDecision,\n\t\tfirstTool: boolean,\n\t): ToolSelectionPendingObservation[\"selection\"] {\n\t\treturn {\n\t\t\tfirstTool,\n\t\t\tdisposition: decision.disposition,\n\t\t\trecommendation: decision.recommendation,\n\t\t\tshortlist: decision.shortlist,\n\t\t\tentropy: decision.entropy,\n\t\t\tmargin: decision.margin,\n\t\t\tranked: decision.ranked.map((candidate) => ({\n\t\t\t\ttool: candidate.tool,\n\t\t\t\tutility: candidate.utility,\n\t\t\t\tprobability: candidate.probability,\n\t\t\t})),\n\t\t};\n\t}\n}\n\nexport { classifyToolIntent, estimateContentTokens, estimateTokens };\n"]}
|