@bendyline/gezel-mcp 1.1.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +16 -2
- package/dist/index.js +6 -0
- package/dist/lint-contracts.js +2 -0
- package/dist/server.d.ts +0 -20
- package/dist/server.js +1907 -1267
- package/package.json +3 -3
package/dist/server.js
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/server.ts
|
|
4
|
+
import {
|
|
5
|
+
AddGezelToProjectInputSchema,
|
|
6
|
+
AdvanceTaskStepInputSchema,
|
|
7
|
+
AppendToFileInputSchema,
|
|
8
|
+
AskUserQuestionInputSchema,
|
|
9
|
+
CreateTaskInputSchema,
|
|
10
|
+
EmptyInputSchema,
|
|
11
|
+
EnsureGezelInputSchema,
|
|
12
|
+
GetScriptRunInputSchema,
|
|
13
|
+
GetTaskInputSchema,
|
|
14
|
+
ListArtifactsInputSchema,
|
|
15
|
+
ListDirectoryInputSchema,
|
|
16
|
+
ListDocumentsInputSchema,
|
|
17
|
+
ListProjectGezelsInputSchema,
|
|
18
|
+
ListScriptsInputSchema,
|
|
19
|
+
ListTasksInputSchema,
|
|
20
|
+
ManageTaskInputSchema,
|
|
21
|
+
MessageGezelInputSchema,
|
|
22
|
+
ReadDocumentInputSchema,
|
|
23
|
+
ReadTaskNotesInputSchema,
|
|
24
|
+
ReplaceInFileInputSchema,
|
|
25
|
+
ReplaceLinesInputSchema,
|
|
26
|
+
RunInstalledScriptInputSchema,
|
|
27
|
+
SaveMemoryInputSchema,
|
|
28
|
+
SearchInputSchema,
|
|
29
|
+
SearchMemoryInputSchema,
|
|
30
|
+
StartProjectInputSchema,
|
|
31
|
+
StepBlueprintSchema,
|
|
32
|
+
UpdateProjectInputSchema,
|
|
33
|
+
WriteArtifactInputSchema,
|
|
34
|
+
WriteDocumentInputSchema,
|
|
35
|
+
WriteFileInputSchema,
|
|
36
|
+
WriteTaskNoteInputSchema
|
|
37
|
+
} from "@bendyline/gezel";
|
|
4
38
|
import { readFileSync } from "fs";
|
|
5
39
|
import {
|
|
6
40
|
AdvanceWhenSchema,
|
|
@@ -14,19 +48,19 @@ import {
|
|
|
14
48
|
NpmRegistryVersionSchema,
|
|
15
49
|
ProviderNameSchema,
|
|
16
50
|
StepGateUnionSchema,
|
|
17
|
-
TaskRefSchema,
|
|
18
|
-
WORKSPACE_READ_MAX_FILES,
|
|
19
|
-
WORKSPACE_READ_MAX_RANGE_LINES,
|
|
20
51
|
applyStepPatch,
|
|
21
52
|
assertCraftbookGraph,
|
|
22
53
|
coerceDeliverableKind,
|
|
54
|
+
composeCraftbookLaunch,
|
|
23
55
|
contextBudgetCeiling,
|
|
24
56
|
craftbookDocFormatFromEnv,
|
|
25
57
|
deliverableStep,
|
|
58
|
+
deniedTaskScopedWrite,
|
|
26
59
|
estimateTokens,
|
|
27
60
|
expandStepDeliverable,
|
|
28
61
|
formatReviewProvenance,
|
|
29
62
|
inferDeliverableKind,
|
|
63
|
+
isOwnerStep,
|
|
30
64
|
isReservedShadowArtifactPath,
|
|
31
65
|
isSafeEntityId,
|
|
32
66
|
isTrustedConstrainedToolset,
|
|
@@ -38,6 +72,9 @@ import {
|
|
|
38
72
|
resolveRoleId,
|
|
39
73
|
resolveSteps,
|
|
40
74
|
stepInsertionIndex,
|
|
75
|
+
stepOwnerGezelId,
|
|
76
|
+
taskOwnedPrefixes,
|
|
77
|
+
taskScopedWriteDeniedMessage,
|
|
41
78
|
uniqueStepId
|
|
42
79
|
} from "@bendyline/gezel";
|
|
43
80
|
import { GezelApiError, GezelClient } from "@bendyline/gezel-client";
|
|
@@ -47,7 +84,18 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
|
|
|
47
84
|
import { z as z6 } from "zod";
|
|
48
85
|
|
|
49
86
|
// src/advance-note.ts
|
|
87
|
+
function advanceStatusLine(opts) {
|
|
88
|
+
const done = `Finished "${opts.completedName}"`;
|
|
89
|
+
if (opts.status === "complete") return `${done}. "${opts.taskTitle}" is complete.`;
|
|
90
|
+
if (opts.status === "paused") return `${done}, but the task paused before the next step.`;
|
|
91
|
+
if (!opts.nextName) return `${done}.`;
|
|
92
|
+
if (opts.ownerStep) return `${done}. Next: "${opts.nextName}", which is waiting for your review.`;
|
|
93
|
+
return `${done}. Next: "${opts.nextName}".`;
|
|
94
|
+
}
|
|
50
95
|
function advanceHandoffNote(opts) {
|
|
96
|
+
if (opts.ownerStep && opts.status === "active") {
|
|
97
|
+
return " It now waits for the user's own review \u2014 they have a card asking them to approve it. Do not work on or advance it. Tell the user it is ready for them, and stop.";
|
|
98
|
+
}
|
|
51
99
|
if (opts.status === "paused") {
|
|
52
100
|
return " The task is now PAUSED \u2014 the new step could not be dispatched, so NO handoff was started. Call `read_task_notes`: the newest note says why it stopped and how to fix it. Tell the user the task is paused and what it needs.";
|
|
53
101
|
}
|
|
@@ -61,96 +109,19 @@ function advanceHandoffNote(opts) {
|
|
|
61
109
|
}
|
|
62
110
|
|
|
63
111
|
// src/assignee-arg.ts
|
|
64
|
-
import { z
|
|
112
|
+
import { z } from "zod";
|
|
65
113
|
|
|
66
114
|
// src/zod-coerce.ts
|
|
67
|
-
import {
|
|
68
|
-
function coerceJsonObject(inner) {
|
|
69
|
-
return z.preprocess((v) => {
|
|
70
|
-
if (typeof v !== "string") return v;
|
|
71
|
-
const trimmed = v.trim();
|
|
72
|
-
if (!trimmed.startsWith("{")) return v;
|
|
73
|
-
try {
|
|
74
|
-
return JSON.parse(trimmed);
|
|
75
|
-
} catch {
|
|
76
|
-
return v;
|
|
77
|
-
}
|
|
78
|
-
}, inner);
|
|
79
|
-
}
|
|
80
|
-
function coerceJsonArray(inner) {
|
|
81
|
-
return z.preprocess((v) => {
|
|
82
|
-
if (typeof v !== "string") return v;
|
|
83
|
-
const trimmed = v.trim();
|
|
84
|
-
if (!trimmed.startsWith("[")) return v;
|
|
85
|
-
try {
|
|
86
|
-
return JSON.parse(trimmed);
|
|
87
|
-
} catch {
|
|
88
|
-
return v;
|
|
89
|
-
}
|
|
90
|
-
}, inner);
|
|
91
|
-
}
|
|
92
|
-
function coerceStringArray(inner) {
|
|
93
|
-
return z.preprocess((v) => {
|
|
94
|
-
if (typeof v !== "string") return v;
|
|
95
|
-
const trimmed = v.trim();
|
|
96
|
-
if (trimmed.length === 0) return [];
|
|
97
|
-
if (trimmed.startsWith("[")) {
|
|
98
|
-
try {
|
|
99
|
-
return JSON.parse(trimmed);
|
|
100
|
-
} catch {
|
|
101
|
-
return v;
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
if (trimmed.startsWith("{")) return v;
|
|
105
|
-
return splitArgv(trimmed);
|
|
106
|
-
}, inner);
|
|
107
|
-
}
|
|
108
|
-
function splitArgv(input) {
|
|
109
|
-
const out = [];
|
|
110
|
-
let current = "";
|
|
111
|
-
let quote = null;
|
|
112
|
-
let escaping = false;
|
|
113
|
-
for (const ch of input) {
|
|
114
|
-
if (escaping) {
|
|
115
|
-
current += ch;
|
|
116
|
-
escaping = false;
|
|
117
|
-
continue;
|
|
118
|
-
}
|
|
119
|
-
if (ch === "\\") {
|
|
120
|
-
escaping = true;
|
|
121
|
-
continue;
|
|
122
|
-
}
|
|
123
|
-
if (quote) {
|
|
124
|
-
if (ch === quote) quote = null;
|
|
125
|
-
else current += ch;
|
|
126
|
-
continue;
|
|
127
|
-
}
|
|
128
|
-
if (ch === '"' || ch === "'") {
|
|
129
|
-
quote = ch;
|
|
130
|
-
continue;
|
|
131
|
-
}
|
|
132
|
-
if (/\s/.test(ch)) {
|
|
133
|
-
if (current.length > 0) {
|
|
134
|
-
out.push(current);
|
|
135
|
-
current = "";
|
|
136
|
-
}
|
|
137
|
-
continue;
|
|
138
|
-
}
|
|
139
|
-
current += ch;
|
|
140
|
-
}
|
|
141
|
-
if (escaping) current += "\\";
|
|
142
|
-
if (current.length > 0) out.push(current);
|
|
143
|
-
return out;
|
|
144
|
-
}
|
|
115
|
+
import { coerceJsonArray, coerceJsonObject, coerceStringArray } from "@bendyline/gezel";
|
|
145
116
|
|
|
146
117
|
// src/assignee-arg.ts
|
|
147
|
-
var AssigneeObjectSchema =
|
|
148
|
-
kind:
|
|
149
|
-
gezelId:
|
|
118
|
+
var AssigneeObjectSchema = z.object({
|
|
119
|
+
kind: z.enum(["gezel", "user"]),
|
|
120
|
+
gezelId: z.string().optional()
|
|
150
121
|
});
|
|
151
122
|
var ASSIGNEE_ARG_DESCRIPTION = `Who owns this \u2014 a gezel id, display name, or role name ("wren", "Rina", "developer"), or the literal "user" for the human. OMIT it when you have no specific gezel in mind: the owner then mirrors whichever gezel the entry step's role resolves to. "gezel" is not a value \u2014 it is the default, and passing it as a placeholder is the same as omitting the argument.`;
|
|
152
123
|
function assigneeArg() {
|
|
153
|
-
return coerceJsonObject(
|
|
124
|
+
return coerceJsonObject(z.union([z.string(), AssigneeObjectSchema])).describe(
|
|
154
125
|
ASSIGNEE_ARG_DESCRIPTION
|
|
155
126
|
);
|
|
156
127
|
}
|
|
@@ -240,6 +211,7 @@ function commandResultIsError(result) {
|
|
|
240
211
|
|
|
241
212
|
// src/craftbook-invocation-idempotency.ts
|
|
242
213
|
import { createHash } from "crypto";
|
|
214
|
+
import { CRAFTBOOK_INVOCATION_KEY_PREFIX, invocationSignature } from "@bendyline/gezel";
|
|
243
215
|
function rootTurnIdFromMessages(sessionId2, messages) {
|
|
244
216
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
245
217
|
const message = messages[index];
|
|
@@ -247,20 +219,8 @@ function rootTurnIdFromMessages(sessionId2, messages) {
|
|
|
247
219
|
}
|
|
248
220
|
return null;
|
|
249
221
|
}
|
|
250
|
-
function canonicalize(value) {
|
|
251
|
-
if (Array.isArray(value)) return value.map(canonicalize);
|
|
252
|
-
if (value && typeof value === "object") {
|
|
253
|
-
return Object.fromEntries(
|
|
254
|
-
Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => [key, canonicalize(entry)])
|
|
255
|
-
);
|
|
256
|
-
}
|
|
257
|
-
return value;
|
|
258
|
-
}
|
|
259
|
-
function invocationSignature(invocation) {
|
|
260
|
-
return JSON.stringify(canonicalize(invocation));
|
|
261
|
-
}
|
|
262
222
|
function rootTurnInvocationKey(rootTurnId, invocation) {
|
|
263
|
-
return
|
|
223
|
+
return `${CRAFTBOOK_INVOCATION_KEY_PREFIX}${createHash("sha256").update(rootTurnId).update("\n").update(invocationSignature(invocation)).digest("hex")}`;
|
|
264
224
|
}
|
|
265
225
|
var RootTurnInvocationCache = class {
|
|
266
226
|
constructor(maxEntries = 128) {
|
|
@@ -292,7 +252,8 @@ ${invocationSignature(args.invocation)}`;
|
|
|
292
252
|
};
|
|
293
253
|
|
|
294
254
|
// src/craftbook-routing.ts
|
|
295
|
-
import {
|
|
255
|
+
import { fillMainContentParam } from "@bendyline/gezel";
|
|
256
|
+
import { z as z2 } from "zod";
|
|
296
257
|
|
|
297
258
|
// src/document-routing.ts
|
|
298
259
|
import { binaryDocumentExtension, isBinaryDocumentPath } from "@bendyline/gezel";
|
|
@@ -408,27 +369,15 @@ function shouldPromoteStartJobToProject(input) {
|
|
|
408
369
|
}
|
|
409
370
|
|
|
410
371
|
// src/craftbook-routing.ts
|
|
411
|
-
var CraftbookInvocationParamsArgSchema = coerceJsonObject(
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
const properties = paramSchema.properties;
|
|
415
|
-
if (!properties || typeof properties !== "object" || Array.isArray(properties)) return {};
|
|
416
|
-
return Object.fromEntries(
|
|
417
|
-
Object.entries(properties).filter(
|
|
418
|
-
(entry) => !!entry[1] && typeof entry[1] === "object" && !Array.isArray(entry[1])
|
|
419
|
-
)
|
|
420
|
-
);
|
|
421
|
-
}
|
|
372
|
+
var CraftbookInvocationParamsArgSchema = coerceJsonObject(z2.record(z2.string(), z2.string())).optional().describe(
|
|
373
|
+
'Invocation parameters declared by the craftbook, such as outputPath. An input param (the files the book works on, e.g. "source") takes a folder or file path in this project workspace; prefix "artifacts:" for one in the artifacts drawer. Files outside the project cannot be passed here \u2014 ask the user to launch the craftbook from Tasks and pick them from their computer.'
|
|
374
|
+
);
|
|
422
375
|
function inferCraftbookJobParams(args) {
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
const suppliedSource = ["sourcePath", "topic", "content"].some(
|
|
429
|
-
(key) => typeof params[key] === "string" && params[key].trim().length > 0
|
|
430
|
-
);
|
|
431
|
-
return suppliedSource ? params : { ...params, topic: jobDescription };
|
|
376
|
+
return fillMainContentParam({
|
|
377
|
+
paramSchema: args.paramSchema,
|
|
378
|
+
...args.params ? { params: args.params } : {},
|
|
379
|
+
...args.jobDescription !== void 0 ? { message: args.jobDescription } : {}
|
|
380
|
+
});
|
|
432
381
|
}
|
|
433
382
|
function suggestedCraftbookInvocation(args) {
|
|
434
383
|
const description = args.query.trim();
|
|
@@ -468,95 +417,18 @@ function binaryDocumentCraftbookRequest(input) {
|
|
|
468
417
|
};
|
|
469
418
|
}
|
|
470
419
|
|
|
471
|
-
// src/
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
next.width = quantizeImageSize(args.width * scale);
|
|
484
|
-
next.height = quantizeImageSize(args.height * scale);
|
|
485
|
-
}
|
|
486
|
-
} else if (typeof args.width === "number" && args.width > AGENT_IMAGE_MAX_SIDE_PX) {
|
|
487
|
-
next.width = AGENT_IMAGE_MAX_SIDE_PX;
|
|
488
|
-
} else if (typeof args.height === "number" && args.height > AGENT_IMAGE_MAX_SIDE_PX) {
|
|
489
|
-
next.height = AGENT_IMAGE_MAX_SIDE_PX;
|
|
490
|
-
}
|
|
491
|
-
if (originalSize && typeof next.width === "number" && typeof next.height === "number" && `${next.width}x${next.height}` !== originalSize) {
|
|
492
|
-
changes.push(`size ${originalSize} -> ${next.width}x${next.height}`);
|
|
493
|
-
} else if (args.width !== next.width && typeof next.width === "number") {
|
|
494
|
-
changes.push(`width ${args.width} -> ${next.width}`);
|
|
495
|
-
} else if (args.height !== next.height && typeof next.height === "number") {
|
|
496
|
-
changes.push(`height ${args.height} -> ${next.height}`);
|
|
497
|
-
}
|
|
498
|
-
if (typeof args.steps === "number" && args.steps > AGENT_IMAGE_MAX_STEPS) {
|
|
499
|
-
next.steps = AGENT_IMAGE_MAX_STEPS;
|
|
500
|
-
changes.push(`steps ${args.steps} -> ${next.steps}`);
|
|
501
|
-
}
|
|
502
|
-
return {
|
|
503
|
-
args: next,
|
|
504
|
-
...changes.length > 0 ? { note: `Request normalized for agent image generation (${changes.join(", ")}).` } : {}
|
|
505
|
-
};
|
|
506
|
-
}
|
|
507
|
-
function quantizeImageSize(size) {
|
|
508
|
-
const rounded = Math.round(size / SIZE_MULTIPLE) * SIZE_MULTIPLE;
|
|
509
|
-
return Math.max(SIZE_MULTIPLE, Math.min(AGENT_IMAGE_MAX_SIDE_PX, rounded));
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
// src/linked-workspace.ts
|
|
513
|
-
function isLinkedWorkspacePath(inputPath) {
|
|
514
|
-
const normalized = inputPath.replaceAll("\\", "/").replace(/\/{2,}/g, "/");
|
|
515
|
-
return normalized === ".." || normalized === "../" || normalized.startsWith("../");
|
|
516
|
-
}
|
|
517
|
-
function resolveLinkedWorkspacePath(sourceProjectId, linkedProjectIds2, inputPath) {
|
|
518
|
-
const normalized = inputPath.replaceAll("\\", "/").replace(/\/{2,}/g, "/");
|
|
519
|
-
if (normalized === ".." || normalized === "../") {
|
|
520
|
-
return { kind: "links-root", projectId: sourceProjectId, path: "..", displayPath: ".." };
|
|
521
|
-
}
|
|
522
|
-
if (!normalized.startsWith("../")) {
|
|
523
|
-
return {
|
|
524
|
-
kind: "current",
|
|
525
|
-
projectId: sourceProjectId,
|
|
526
|
-
path: normalized,
|
|
527
|
-
displayPath: normalized
|
|
528
|
-
};
|
|
529
|
-
}
|
|
530
|
-
const remainder = normalized.slice(3);
|
|
531
|
-
const slash = remainder.indexOf("/");
|
|
532
|
-
const targetProjectId = slash === -1 ? remainder : remainder.slice(0, slash);
|
|
533
|
-
const targetPath = slash === -1 ? "" : remainder.slice(slash + 1);
|
|
534
|
-
if (!targetProjectId || !linkedProjectIds2.includes(targetProjectId)) {
|
|
535
|
-
const available = linkedProjectIds2.length > 0 ? linkedProjectIds2.join(", ") : "none";
|
|
536
|
-
throw new Error(
|
|
537
|
-
`project "${targetProjectId || "(missing)"}" is not linked from ${sourceProjectId}; linked projects: ${available}`
|
|
538
|
-
);
|
|
539
|
-
}
|
|
540
|
-
return {
|
|
541
|
-
kind: "linked",
|
|
542
|
-
projectId: targetProjectId,
|
|
543
|
-
path: targetPath,
|
|
544
|
-
displayPath: linkedDisplayPath(targetProjectId, targetPath),
|
|
545
|
-
linkedFromProjectId: sourceProjectId
|
|
546
|
-
};
|
|
547
|
-
}
|
|
548
|
-
function linkedDisplayPath(projectId2, path) {
|
|
549
|
-
return path ? `../${projectId2}/${path}` : `../${projectId2}`;
|
|
550
|
-
}
|
|
551
|
-
function linkedProjectEntries(projectIds) {
|
|
552
|
-
return projectIds.map((id) => ({ name: id, path: `../${id}`, isDirectory: true }));
|
|
553
|
-
}
|
|
554
|
-
function prefixLinkedEntry(projectId2, entry) {
|
|
555
|
-
return {
|
|
556
|
-
...entry,
|
|
557
|
-
path: linkedDisplayPath(projectId2, entry.path)
|
|
558
|
-
};
|
|
559
|
-
}
|
|
420
|
+
// src/cross-drawer-read-tools.ts
|
|
421
|
+
import {
|
|
422
|
+
WORKSPACE_READ_MAX_FILES,
|
|
423
|
+
WORKSPACE_READ_MAX_RANGE_LINES
|
|
424
|
+
} from "@bendyline/gezel";
|
|
425
|
+
import {
|
|
426
|
+
ReadArtifactInputSchema,
|
|
427
|
+
ReadFileInputSchema,
|
|
428
|
+
binaryDocumentExtension as binaryDocumentExtension2,
|
|
429
|
+
isBinaryDocumentPath as isBinaryDocumentPath2
|
|
430
|
+
} from "@bendyline/gezel";
|
|
431
|
+
import { z as z4 } from "zod";
|
|
560
432
|
|
|
561
433
|
// src/near-miss.ts
|
|
562
434
|
function closestFileNames(target, names, limit = 3) {
|
|
@@ -579,310 +451,55 @@ function closestFileNames(target, names, limit = 3) {
|
|
|
579
451
|
return scored.slice(0, limit).map((e) => e.name);
|
|
580
452
|
}
|
|
581
453
|
|
|
582
|
-
// src/
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
return out.join("");
|
|
454
|
+
// src/reanchor.ts
|
|
455
|
+
var REANCHOR_CONTEXT_LINES = 4;
|
|
456
|
+
var REANCHOR_MAX_CHARS = 1400;
|
|
457
|
+
function withLineNumbers(content, startAt = 1) {
|
|
458
|
+
if (content === "") return "";
|
|
459
|
+
const hadTrailingNewline = content.endsWith("\n");
|
|
460
|
+
const body = hadTrailingNewline ? content.slice(0, -1) : content;
|
|
461
|
+
const lines = body.split("\n");
|
|
462
|
+
const width = String(startAt + lines.length - 1).length;
|
|
463
|
+
const numbered = lines.map((line, i) => `${String(startAt + i).padStart(width)}\u2192${line}`).join("\n");
|
|
464
|
+
return hadTrailingNewline ? `${numbered}
|
|
465
|
+
` : numbered;
|
|
595
466
|
}
|
|
596
|
-
function
|
|
597
|
-
const
|
|
598
|
-
|
|
599
|
-
let last = 0;
|
|
600
|
-
for (const m of input.matchAll(fenceRe)) {
|
|
601
|
-
const idx = m.index ?? 0;
|
|
602
|
-
if (idx > last) {
|
|
603
|
-
segments.push({ fenced: false, text: input.slice(last, idx) });
|
|
604
|
-
}
|
|
605
|
-
segments.push({ fenced: true, text: m[0] });
|
|
606
|
-
last = idx + m[0].length;
|
|
607
|
-
}
|
|
608
|
-
if (last < input.length) {
|
|
609
|
-
segments.push({ fenced: false, text: input.slice(last) });
|
|
610
|
-
}
|
|
611
|
-
return segments;
|
|
467
|
+
function editReanchorDisabled(env = process.env) {
|
|
468
|
+
const raw = env.GEZEL_DISABLE_EDIT_REANCHOR;
|
|
469
|
+
return raw === "1" || raw?.toLowerCase() === "true";
|
|
612
470
|
}
|
|
613
|
-
function
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
if (
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
if (line.endsWith(" ")) {
|
|
632
|
-
if (buf.length) buf.push(trimmed);
|
|
633
|
-
else buf.push(line);
|
|
634
|
-
flush();
|
|
635
|
-
continue;
|
|
636
|
-
}
|
|
637
|
-
if (isStandaloneBlock(trimmed)) {
|
|
638
|
-
flush();
|
|
639
|
-
result.push(line.replace(/\s+$/, ""));
|
|
640
|
-
continue;
|
|
641
|
-
}
|
|
642
|
-
if (isContinuableBlock(trimmed)) {
|
|
643
|
-
flush();
|
|
644
|
-
buf.push(line.replace(/\s+$/, ""));
|
|
645
|
-
continue;
|
|
471
|
+
async function reanchorAfterEdit(args) {
|
|
472
|
+
if (editReanchorDisabled(args.env ?? process.env)) return "";
|
|
473
|
+
try {
|
|
474
|
+
const content = await args.readFile();
|
|
475
|
+
if (content === "") return "";
|
|
476
|
+
const body = content.endsWith("\n") ? content.slice(0, -1) : content;
|
|
477
|
+
const lines = body.split("\n");
|
|
478
|
+
const delta = args.addedLines - args.removedLines;
|
|
479
|
+
const from = Math.max(1, args.startLine - REANCHOR_CONTEXT_LINES);
|
|
480
|
+
const through = Math.min(
|
|
481
|
+
lines.length,
|
|
482
|
+
args.startLine + Math.max(args.addedLines, 1) - 1 + REANCHOR_CONTEXT_LINES
|
|
483
|
+
);
|
|
484
|
+
if (through < from) return "";
|
|
485
|
+
let window = withLineNumbers(lines.slice(from - 1, through).join("\n"), from);
|
|
486
|
+
if (window.length > REANCHOR_MAX_CHARS) {
|
|
487
|
+
window = `${window.slice(0, REANCHOR_MAX_CHARS)}
|
|
488
|
+
\u2026 (window truncated; re-read for the rest)`;
|
|
646
489
|
}
|
|
647
|
-
|
|
490
|
+
const shift = delta === 0 ? "Line numbers elsewhere in the file are unchanged." : `Every line after ${args.startLine} shifted by ${delta > 0 ? "+" : ""}${delta} \u2014 line numbers from an earlier read_file are stale past that point.`;
|
|
491
|
+
return `
|
|
492
|
+
|
|
493
|
+
${shift}
|
|
494
|
+
${args.path} now reads:
|
|
495
|
+
${window}`;
|
|
496
|
+
} catch {
|
|
497
|
+
return "";
|
|
648
498
|
}
|
|
649
|
-
flush();
|
|
650
|
-
return result.join("\n");
|
|
651
|
-
}
|
|
652
|
-
function isStandaloneBlock(trimmed) {
|
|
653
|
-
if (/^#{1,6}\s/.test(trimmed)) return true;
|
|
654
|
-
if (/^-{3,}$|^={3,}$|^\*{3,}$|^_{3,}$/.test(trimmed)) return true;
|
|
655
|
-
return false;
|
|
656
|
-
}
|
|
657
|
-
function isContinuableBlock(trimmed) {
|
|
658
|
-
if (/^(?:[-*+])\s/.test(trimmed)) return true;
|
|
659
|
-
if (/^\d+[.)]\s/.test(trimmed)) return true;
|
|
660
|
-
if (/^>/.test(trimmed)) return true;
|
|
661
|
-
if (/^\|/.test(trimmed)) return true;
|
|
662
|
-
return false;
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
// src/partial-edits.ts
|
|
666
|
-
var CAP = 12;
|
|
667
|
-
var GATED_TOOLS = /* @__PURE__ */ new Set(["advance_task_step", "verify_outcome"]);
|
|
668
|
-
var PartialEditRegistry = class {
|
|
669
|
-
drafts = /* @__PURE__ */ new Map();
|
|
670
|
-
/**
|
|
671
|
-
* Record a provisional edit. `priorContent` is only kept the first
|
|
672
|
-
* time — it is the last state the file was in before the sequence
|
|
673
|
-
* started, not the previous provisional step.
|
|
674
|
-
*/
|
|
675
|
-
record(path, priorContent) {
|
|
676
|
-
const existing = this.drafts.get(path);
|
|
677
|
-
if (existing) {
|
|
678
|
-
existing.edits += 1;
|
|
679
|
-
return existing;
|
|
680
|
-
}
|
|
681
|
-
const created = { path, edits: 1, snapshot: priorContent };
|
|
682
|
-
this.drafts.set(path, created);
|
|
683
|
-
return created;
|
|
684
|
-
}
|
|
685
|
-
get(path) {
|
|
686
|
-
return this.drafts.get(path);
|
|
687
|
-
}
|
|
688
|
-
isOpen(path) {
|
|
689
|
-
return this.drafts.has(path);
|
|
690
|
-
}
|
|
691
|
-
/** Called when a path validates cleanly again, by any write path. */
|
|
692
|
-
close(path) {
|
|
693
|
-
const draft = this.drafts.get(path);
|
|
694
|
-
if (draft) this.drafts.delete(path);
|
|
695
|
-
return draft;
|
|
696
|
-
}
|
|
697
|
-
openPaths() {
|
|
698
|
-
return [...this.drafts.keys()].sort();
|
|
699
|
-
}
|
|
700
|
-
/**
|
|
701
|
-
* Why `toolName` may not run, or null. Mirrors the unresolved-tool
|
|
702
|
-
* failure ledger: narrow set of gated tools, and `set_task_status`
|
|
703
|
-
* stays open so a stuck gezel keeps an honest exit.
|
|
704
|
-
*/
|
|
705
|
-
blockReason(toolName) {
|
|
706
|
-
if (!GATED_TOOLS.has(toolName)) return null;
|
|
707
|
-
const open = this.openPaths();
|
|
708
|
-
if (open.length === 0) return null;
|
|
709
|
-
const list = open.map((p) => `\`${p}\``).join(", ");
|
|
710
|
-
return [
|
|
711
|
-
`${toolName} is blocked: ${open.length === 1 ? "a file is" : "files are"} still in a provisional edit sequence (${list}).`,
|
|
712
|
-
"Those edits were accepted without the syntax gate because you passed `partial: true`, so the file is not known to parse.",
|
|
713
|
-
"Finish the sequence with a final edit that omits `partial`, or re-emit the whole file with `write_file`.",
|
|
714
|
-
`Then re-run \`validate\` and call ${toolName} again.`
|
|
715
|
-
].join(" ");
|
|
716
|
-
}
|
|
717
|
-
/** Model-facing note appended to a provisional edit's result. */
|
|
718
|
-
noticeFor(draft) {
|
|
719
|
-
const left = CAP - draft.edits;
|
|
720
|
-
const parts = [
|
|
721
|
-
`[Provisional edit ${draft.edits} of at most ${CAP}] \`${draft.path}\` is a draft and was NOT syntax-checked.`,
|
|
722
|
-
"Nothing that declares work finished will run until it parses again.",
|
|
723
|
-
`Close the sequence with a final edit that omits \`partial\`, then call \`validate({ path: "${draft.path}" })\`.`
|
|
724
|
-
];
|
|
725
|
-
if (left <= 3) {
|
|
726
|
-
parts.push(`Only ${left} provisional edit(s) remain before the sequence is reverted.`);
|
|
727
|
-
}
|
|
728
|
-
return `
|
|
729
|
-
|
|
730
|
-
${parts.join(" ")}`;
|
|
731
|
-
}
|
|
732
|
-
};
|
|
733
|
-
|
|
734
|
-
// src/platform-tool-availability.ts
|
|
735
|
-
import { spawnSync } from "child_process";
|
|
736
|
-
var DENY_NET_TOOLS = ["run_nodejs_script", "derive_file"];
|
|
737
|
-
var linuxSystemdProbe;
|
|
738
|
-
function canUseLinuxSystemdDenyNet() {
|
|
739
|
-
if (process.platform !== "linux") return false;
|
|
740
|
-
if (linuxSystemdProbe !== void 0) return linuxSystemdProbe;
|
|
741
|
-
const probe = "const net=require('node:net');const s=net.connect({host:'127.0.0.1',port:9});s.once('connect',()=>process.exit(9));s.once('error',e=>process.exit(['EAFNOSUPPORT','EPERM','EACCES'].includes(e.code)?0:2));setTimeout(()=>process.exit(3),1000);";
|
|
742
|
-
const result = spawnSync(
|
|
743
|
-
"systemd-run",
|
|
744
|
-
[
|
|
745
|
-
"--user",
|
|
746
|
-
"--quiet",
|
|
747
|
-
"--pipe",
|
|
748
|
-
"--wait",
|
|
749
|
-
"--collect",
|
|
750
|
-
"-p",
|
|
751
|
-
"RestrictAddressFamilies=AF_UNIX",
|
|
752
|
-
"-p",
|
|
753
|
-
"RuntimeMaxSec=3",
|
|
754
|
-
"--",
|
|
755
|
-
process.execPath,
|
|
756
|
-
"-e",
|
|
757
|
-
probe
|
|
758
|
-
],
|
|
759
|
-
{ stdio: "ignore", timeout: 3e3 }
|
|
760
|
-
);
|
|
761
|
-
linuxSystemdProbe = result.status === 0;
|
|
762
|
-
return linuxSystemdProbe;
|
|
763
|
-
}
|
|
764
|
-
function unavailableToolsForPlatform(platform, options = {}) {
|
|
765
|
-
if (platform === "darwin") return [];
|
|
766
|
-
if (platform === "linux" && (options.linuxSystemdAvailable ?? canUseLinuxSystemdDenyNet())) {
|
|
767
|
-
return [];
|
|
768
|
-
}
|
|
769
|
-
return DENY_NET_TOOLS;
|
|
770
|
-
}
|
|
771
|
-
|
|
772
|
-
// src/question-prompt.ts
|
|
773
|
-
function composeQuestionPrompt(parts) {
|
|
774
|
-
const unique = [];
|
|
775
|
-
for (const value of [parts.question, parts.prompt, parts.description]) {
|
|
776
|
-
const trimmed = value?.trim();
|
|
777
|
-
if (trimmed && !unique.includes(trimmed)) unique.push(trimmed);
|
|
778
|
-
}
|
|
779
|
-
return unique.join("\n\n");
|
|
780
|
-
}
|
|
781
|
-
function resolveQuestionTaskRef(explicitTaskRef, sessionTaskRef2) {
|
|
782
|
-
return explicitTaskRef ?? (sessionTaskRef2.trim() || void 0);
|
|
783
499
|
}
|
|
784
500
|
|
|
785
|
-
// src/reanchor.ts
|
|
786
|
-
var REANCHOR_CONTEXT_LINES = 4;
|
|
787
|
-
var REANCHOR_MAX_CHARS = 1400;
|
|
788
|
-
function withLineNumbers(content, startAt = 1) {
|
|
789
|
-
if (content === "") return "";
|
|
790
|
-
const hadTrailingNewline = content.endsWith("\n");
|
|
791
|
-
const body = hadTrailingNewline ? content.slice(0, -1) : content;
|
|
792
|
-
const lines = body.split("\n");
|
|
793
|
-
const width = String(startAt + lines.length - 1).length;
|
|
794
|
-
const numbered = lines.map((line, i) => `${String(startAt + i).padStart(width)}\u2192${line}`).join("\n");
|
|
795
|
-
return hadTrailingNewline ? `${numbered}
|
|
796
|
-
` : numbered;
|
|
797
|
-
}
|
|
798
|
-
function editReanchorDisabled(env = process.env) {
|
|
799
|
-
const raw = env.GEZEL_DISABLE_EDIT_REANCHOR;
|
|
800
|
-
return raw === "1" || raw?.toLowerCase() === "true";
|
|
801
|
-
}
|
|
802
|
-
async function reanchorAfterEdit(args) {
|
|
803
|
-
if (editReanchorDisabled(args.env ?? process.env)) return "";
|
|
804
|
-
try {
|
|
805
|
-
const content = await args.readFile();
|
|
806
|
-
if (content === "") return "";
|
|
807
|
-
const body = content.endsWith("\n") ? content.slice(0, -1) : content;
|
|
808
|
-
const lines = body.split("\n");
|
|
809
|
-
const delta = args.addedLines - args.removedLines;
|
|
810
|
-
const from = Math.max(1, args.startLine - REANCHOR_CONTEXT_LINES);
|
|
811
|
-
const through = Math.min(
|
|
812
|
-
lines.length,
|
|
813
|
-
args.startLine + Math.max(args.addedLines, 1) - 1 + REANCHOR_CONTEXT_LINES
|
|
814
|
-
);
|
|
815
|
-
if (through < from) return "";
|
|
816
|
-
let window = withLineNumbers(lines.slice(from - 1, through).join("\n"), from);
|
|
817
|
-
if (window.length > REANCHOR_MAX_CHARS) {
|
|
818
|
-
window = `${window.slice(0, REANCHOR_MAX_CHARS)}
|
|
819
|
-
\u2026 (window truncated; re-read for the rest)`;
|
|
820
|
-
}
|
|
821
|
-
const shift = delta === 0 ? "Line numbers elsewhere in the file are unchanged." : `Every line after ${args.startLine} shifted by ${delta > 0 ? "+" : ""}${delta} \u2014 line numbers from an earlier read_file are stale past that point.`;
|
|
822
|
-
return `
|
|
823
|
-
|
|
824
|
-
${shift}
|
|
825
|
-
${args.path} now reads:
|
|
826
|
-
${window}`;
|
|
827
|
-
} catch {
|
|
828
|
-
return "";
|
|
829
|
-
}
|
|
830
|
-
}
|
|
831
|
-
|
|
832
|
-
// src/repo-intake-policy.ts
|
|
833
|
-
var GITHUB_REPO_URL_RE = /https?:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]*[A-Za-z0-9_-])(?:\.git)?(?:\/[^\s)"'`<>]*)?/i;
|
|
834
|
-
function extractGitHubRepoUrl(text) {
|
|
835
|
-
const match = text.match(GITHUB_REPO_URL_RE);
|
|
836
|
-
if (!match) return void 0;
|
|
837
|
-
const owner = match[1];
|
|
838
|
-
const repo = match[2]?.replace(/\.git$/i, "");
|
|
839
|
-
if (!owner || !repo) return void 0;
|
|
840
|
-
return `https://github.com/${owner}/${repo}`;
|
|
841
|
-
}
|
|
842
|
-
function knownRepoShortcut(text) {
|
|
843
|
-
if (/\bsquisq\b/i.test(text)) {
|
|
844
|
-
return { url: "https://github.com/bendyline/squisq", projectName: "Squisq Code Review" };
|
|
845
|
-
}
|
|
846
|
-
return null;
|
|
847
|
-
}
|
|
848
|
-
function titleCaseRepoName(repo) {
|
|
849
|
-
return repo.split(/[-_\s]+/).filter(Boolean).map((part) => `${part.slice(0, 1).toUpperCase()}${part.slice(1).toLowerCase()}`).join(" ");
|
|
850
|
-
}
|
|
851
|
-
function projectNameFromUrl(url) {
|
|
852
|
-
const repo = url.split("/").pop() || "Repository";
|
|
853
|
-
return `${titleCaseRepoName(repo)} Code Review`;
|
|
854
|
-
}
|
|
855
|
-
function looksLikeRepoSourceWork(text, hasUrl) {
|
|
856
|
-
if (/\b(review|audit|analy[sz]e|analysis|inspect|architecture|codebase|source code|walk the source|read (?:the )?source|fix|debug|change|work with)\b/i.test(
|
|
857
|
-
text
|
|
858
|
-
)) {
|
|
859
|
-
return true;
|
|
860
|
-
}
|
|
861
|
-
return hasUrl && /\b(repo|repository|clone|fetch_repo)\b/i.test(text);
|
|
862
|
-
}
|
|
863
|
-
function repoIntakeRedirect(input) {
|
|
864
|
-
const url = extractGitHubRepoUrl(input.text);
|
|
865
|
-
const shortcut = url ? null : knownRepoShortcut(input.text);
|
|
866
|
-
const targetUrl = url ?? shortcut?.url;
|
|
867
|
-
if (!targetUrl || !looksLikeRepoSourceWork(input.text, Boolean(url))) return null;
|
|
868
|
-
const projectName = input.projectName?.trim() || shortcut?.projectName || projectNameFromUrl(targetUrl);
|
|
869
|
-
const fetchCall = `fetch_repo({ url: "${targetUrl}", projectName: "${projectName}" })`;
|
|
870
|
-
const prefix = input.mode === "macro" ? `${input.tool} is the wrong macro for remote repository review/analysis because it creates an empty bootstrap project with no source code.` : `${input.tool} cannot hand off remote repository work from this project until the source repository has been fetched.`;
|
|
871
|
-
return {
|
|
872
|
-
url: targetUrl,
|
|
873
|
-
projectName,
|
|
874
|
-
message: `${prefix} Call \`${fetchCall}\` first; that creates the project and clones the repository into the workspace root. After it returns, pass the returned projectId to any reviewer or specialist. Do not ask the user to paste source code.`
|
|
875
|
-
};
|
|
876
|
-
}
|
|
877
|
-
|
|
878
|
-
// src/script-tools.ts
|
|
879
|
-
import {
|
|
880
|
-
ProjectTypeToolSchema
|
|
881
|
-
} from "@bendyline/gezel";
|
|
882
|
-
import { z as z5 } from "zod";
|
|
883
|
-
|
|
884
501
|
// src/tool-contracts.ts
|
|
885
|
-
import { z as
|
|
502
|
+
import { z as z3 } from "zod";
|
|
886
503
|
|
|
887
504
|
// src/tool-inventory.ts
|
|
888
505
|
import { resolveDistributionProfile } from "@bendyline/gezel";
|
|
@@ -919,6 +536,7 @@ var ALWAYS_REGISTERED_TOOLS = [
|
|
|
919
536
|
// Artifacts (project-scoped)
|
|
920
537
|
"list_artifacts",
|
|
921
538
|
"read_artifact",
|
|
539
|
+
"read_artifacts",
|
|
922
540
|
"write_artifact",
|
|
923
541
|
"grep_artifact",
|
|
924
542
|
"browser_find_page_element",
|
|
@@ -991,6 +609,7 @@ var ALWAYS_REGISTERED_TOOLS = [
|
|
|
991
609
|
"spawn_task_instances",
|
|
992
610
|
"list_task_children",
|
|
993
611
|
"set_task_status",
|
|
612
|
+
"manage_task",
|
|
994
613
|
"activate_task",
|
|
995
614
|
"assign_task",
|
|
996
615
|
"add_task_step",
|
|
@@ -1016,6 +635,7 @@ var ALWAYS_REGISTERED_TOOLS = [
|
|
|
1016
635
|
"fetch_url",
|
|
1017
636
|
"web_search",
|
|
1018
637
|
"wikipedia_search",
|
|
638
|
+
"wikimedia_image_search",
|
|
1019
639
|
"wikipedia_read",
|
|
1020
640
|
// Search / files
|
|
1021
641
|
"search",
|
|
@@ -1283,176 +903,181 @@ function resolveToolNameSpelling(requested, knownNames) {
|
|
|
1283
903
|
}
|
|
1284
904
|
|
|
1285
905
|
// src/tool-contracts.ts
|
|
1286
|
-
var ToolResultSummarySchema =
|
|
1287
|
-
summary:
|
|
906
|
+
var ToolResultSummarySchema = z3.object({
|
|
907
|
+
summary: z3.string().min(1)
|
|
1288
908
|
});
|
|
1289
|
-
var SearchMatchSchema =
|
|
1290
|
-
path:
|
|
1291
|
-
line:
|
|
1292
|
-
lineStart:
|
|
1293
|
-
lineEnd:
|
|
1294
|
-
text:
|
|
1295
|
-
snippet:
|
|
1296
|
-
name:
|
|
1297
|
-
source:
|
|
1298
|
-
score:
|
|
1299
|
-
day:
|
|
1300
|
-
scope:
|
|
1301
|
-
before:
|
|
1302
|
-
after:
|
|
1303
|
-
}).catchall(
|
|
1304
|
-
var SearchCraftbookSuggestionSchema =
|
|
1305
|
-
id:
|
|
1306
|
-
name:
|
|
1307
|
-
description:
|
|
1308
|
-
source:
|
|
1309
|
-
version:
|
|
1310
|
-
stepCount:
|
|
1311
|
-
score:
|
|
1312
|
-
invocation:
|
|
1313
|
-
tool:
|
|
1314
|
-
arguments:
|
|
1315
|
-
craftbookId:
|
|
1316
|
-
description:
|
|
909
|
+
var SearchMatchSchema = z3.object({
|
|
910
|
+
path: z3.string().optional(),
|
|
911
|
+
line: z3.number().int().positive().optional(),
|
|
912
|
+
lineStart: z3.number().int().positive().optional(),
|
|
913
|
+
lineEnd: z3.number().int().positive().optional(),
|
|
914
|
+
text: z3.string().optional(),
|
|
915
|
+
snippet: z3.string().optional(),
|
|
916
|
+
name: z3.string().optional(),
|
|
917
|
+
source: z3.string().optional(),
|
|
918
|
+
score: z3.number().optional(),
|
|
919
|
+
day: z3.string().optional(),
|
|
920
|
+
scope: z3.string().optional(),
|
|
921
|
+
before: z3.array(z3.object({ line: z3.number().int().positive(), text: z3.string() })).optional(),
|
|
922
|
+
after: z3.array(z3.object({ line: z3.number().int().positive(), text: z3.string() })).optional()
|
|
923
|
+
}).catchall(z3.unknown());
|
|
924
|
+
var SearchCraftbookSuggestionSchema = z3.object({
|
|
925
|
+
id: z3.string(),
|
|
926
|
+
name: z3.string(),
|
|
927
|
+
description: z3.string().optional(),
|
|
928
|
+
source: z3.enum(["bundled", "local", "project"]),
|
|
929
|
+
version: z3.string().optional(),
|
|
930
|
+
stepCount: z3.number().int().nonnegative(),
|
|
931
|
+
score: z3.number(),
|
|
932
|
+
invocation: z3.object({
|
|
933
|
+
tool: z3.literal("invoke_craftbook"),
|
|
934
|
+
arguments: z3.object({
|
|
935
|
+
craftbookId: z3.string(),
|
|
936
|
+
description: z3.string()
|
|
1317
937
|
})
|
|
1318
938
|
})
|
|
1319
939
|
});
|
|
1320
|
-
var ListItemSchema =
|
|
1321
|
-
id:
|
|
1322
|
-
ref:
|
|
1323
|
-
path:
|
|
1324
|
-
name:
|
|
1325
|
-
title:
|
|
1326
|
-
role:
|
|
1327
|
-
version:
|
|
1328
|
-
command:
|
|
1329
|
-
status:
|
|
1330
|
-
isDirectory:
|
|
1331
|
-
}).catchall(
|
|
940
|
+
var ListItemSchema = z3.object({
|
|
941
|
+
id: z3.string().optional(),
|
|
942
|
+
ref: z3.string().optional(),
|
|
943
|
+
path: z3.string().optional(),
|
|
944
|
+
name: z3.string().optional(),
|
|
945
|
+
title: z3.string().optional(),
|
|
946
|
+
role: z3.string().optional(),
|
|
947
|
+
version: z3.string().optional(),
|
|
948
|
+
command: z3.string().optional(),
|
|
949
|
+
status: z3.string().optional(),
|
|
950
|
+
isDirectory: z3.boolean().optional()
|
|
951
|
+
}).catchall(z3.unknown());
|
|
1332
952
|
var SearchToolOutputSchema = ToolResultSummarySchema.extend({
|
|
1333
|
-
query:
|
|
1334
|
-
matches:
|
|
1335
|
-
count:
|
|
1336
|
-
truncated:
|
|
1337
|
-
engine:
|
|
1338
|
-
mode:
|
|
1339
|
-
nextCursor:
|
|
1340
|
-
truncationReason:
|
|
953
|
+
query: z3.string().optional(),
|
|
954
|
+
matches: z3.array(SearchMatchSchema),
|
|
955
|
+
count: z3.number().int().nonnegative(),
|
|
956
|
+
truncated: z3.boolean().optional(),
|
|
957
|
+
engine: z3.string().optional(),
|
|
958
|
+
mode: z3.string().optional(),
|
|
959
|
+
nextCursor: z3.number().int().nonnegative().optional(),
|
|
960
|
+
truncationReason: z3.string().optional(),
|
|
1341
961
|
/** Present only on omni-search; omitted by narrower compatibility tools. */
|
|
1342
|
-
craftbooks:
|
|
962
|
+
craftbooks: z3.array(SearchCraftbookSuggestionSchema).optional()
|
|
1343
963
|
});
|
|
1344
964
|
var ListToolOutputSchema = ToolResultSummarySchema.extend({
|
|
1345
|
-
items:
|
|
1346
|
-
count:
|
|
1347
|
-
truncated:
|
|
1348
|
-
packageManager:
|
|
965
|
+
items: z3.array(ListItemSchema),
|
|
966
|
+
count: z3.number().int().nonnegative(),
|
|
967
|
+
truncated: z3.boolean().optional(),
|
|
968
|
+
packageManager: z3.string().optional()
|
|
1349
969
|
});
|
|
1350
970
|
var TableDescribeToolOutputSchema = ToolResultSummarySchema.extend({
|
|
1351
|
-
table:
|
|
1352
|
-
markdown:
|
|
1353
|
-
rows:
|
|
1354
|
-
columns:
|
|
1355
|
-
schemaInferred:
|
|
971
|
+
table: z3.string(),
|
|
972
|
+
markdown: z3.string(),
|
|
973
|
+
rows: z3.number().int().nonnegative(),
|
|
974
|
+
columns: z3.number().int().nonnegative(),
|
|
975
|
+
schemaInferred: z3.boolean().optional()
|
|
1356
976
|
});
|
|
1357
977
|
var TableQueryToolOutputSchema = ToolResultSummarySchema.extend({
|
|
1358
|
-
rows:
|
|
1359
|
-
columns:
|
|
1360
|
-
count:
|
|
1361
|
-
truncated:
|
|
1362
|
-
limit:
|
|
1363
|
-
tablesInScope:
|
|
978
|
+
rows: z3.array(z3.record(z3.string(), z3.unknown())),
|
|
979
|
+
columns: z3.array(z3.string()),
|
|
980
|
+
count: z3.number().int().nonnegative(),
|
|
981
|
+
truncated: z3.boolean().optional(),
|
|
982
|
+
limit: z3.number().int().positive().optional(),
|
|
983
|
+
tablesInScope: z3.array(z3.string()).optional()
|
|
1364
984
|
});
|
|
1365
985
|
var StatToolOutputSchema = ToolResultSummarySchema.extend({
|
|
1366
|
-
path:
|
|
1367
|
-
kind:
|
|
1368
|
-
size:
|
|
1369
|
-
mtime:
|
|
986
|
+
path: z3.string(),
|
|
987
|
+
kind: z3.enum(["file", "dir", "missing"]),
|
|
988
|
+
size: z3.number().int().nonnegative().optional(),
|
|
989
|
+
mtime: z3.string().optional()
|
|
1370
990
|
});
|
|
1371
|
-
var TaskRecordSchema =
|
|
1372
|
-
ref:
|
|
1373
|
-
title:
|
|
1374
|
-
status:
|
|
1375
|
-
activeStepId:
|
|
1376
|
-
assignee:
|
|
1377
|
-
craftbook:
|
|
1378
|
-
}).catchall(
|
|
991
|
+
var TaskRecordSchema = z3.object({
|
|
992
|
+
ref: z3.string().optional(),
|
|
993
|
+
title: z3.string().optional(),
|
|
994
|
+
status: z3.string().optional(),
|
|
995
|
+
activeStepId: z3.string().nullable().optional(),
|
|
996
|
+
assignee: z3.record(z3.string(), z3.unknown()).optional(),
|
|
997
|
+
craftbook: z3.record(z3.string(), z3.unknown()).optional()
|
|
998
|
+
}).catchall(z3.unknown());
|
|
1379
999
|
var TaskToolOutputSchema = ToolResultSummarySchema.extend({
|
|
1380
|
-
operation:
|
|
1381
|
-
ref:
|
|
1382
|
-
status:
|
|
1383
|
-
stepId:
|
|
1000
|
+
operation: z3.string(),
|
|
1001
|
+
ref: z3.string().optional(),
|
|
1002
|
+
status: z3.string().optional(),
|
|
1003
|
+
stepId: z3.string().optional(),
|
|
1384
1004
|
task: TaskRecordSchema.nullable().optional(),
|
|
1385
|
-
tasks:
|
|
1386
|
-
count:
|
|
1005
|
+
tasks: z3.array(TaskRecordSchema).optional(),
|
|
1006
|
+
count: z3.number().int().nonnegative().optional(),
|
|
1387
1007
|
note: TaskRecordSchema.optional(),
|
|
1388
|
-
details:
|
|
1008
|
+
details: z3.record(z3.string(), z3.unknown()).optional()
|
|
1389
1009
|
});
|
|
1390
1010
|
var ExecutionToolOutputSchema = ToolResultSummarySchema.extend({
|
|
1391
|
-
state:
|
|
1392
|
-
ok:
|
|
1393
|
-
code:
|
|
1394
|
-
stdout:
|
|
1395
|
-
stderr:
|
|
1396
|
-
stdoutTruncated:
|
|
1397
|
-
stderrTruncated:
|
|
1398
|
-
timedOut:
|
|
1399
|
-
error:
|
|
1400
|
-
approvalPending:
|
|
1401
|
-
questionId:
|
|
1402
|
-
declined:
|
|
1403
|
-
resolvedBinPath:
|
|
1404
|
-
runId:
|
|
1405
|
-
calls:
|
|
1406
|
-
logs:
|
|
1407
|
-
output:
|
|
1011
|
+
state: z3.enum(["completed", "approval_pending", "running", "failed"]),
|
|
1012
|
+
ok: z3.boolean(),
|
|
1013
|
+
code: z3.number().int().optional(),
|
|
1014
|
+
stdout: z3.string().optional(),
|
|
1015
|
+
stderr: z3.string().optional(),
|
|
1016
|
+
stdoutTruncated: z3.boolean().optional(),
|
|
1017
|
+
stderrTruncated: z3.boolean().optional(),
|
|
1018
|
+
timedOut: z3.boolean().optional(),
|
|
1019
|
+
error: z3.string().optional(),
|
|
1020
|
+
approvalPending: z3.boolean().optional(),
|
|
1021
|
+
questionId: z3.string().optional(),
|
|
1022
|
+
declined: z3.string().optional(),
|
|
1023
|
+
resolvedBinPath: z3.string().optional(),
|
|
1024
|
+
runId: z3.string().optional(),
|
|
1025
|
+
calls: z3.array(z3.record(z3.string(), z3.unknown())).optional(),
|
|
1026
|
+
logs: z3.string().optional(),
|
|
1027
|
+
output: z3.unknown().optional()
|
|
1408
1028
|
});
|
|
1409
1029
|
var GitToolOutputSchema = ExecutionToolOutputSchema.extend({
|
|
1410
|
-
command:
|
|
1411
|
-
args:
|
|
1030
|
+
command: z3.literal("git"),
|
|
1031
|
+
args: z3.array(z3.string())
|
|
1412
1032
|
});
|
|
1413
1033
|
var MemorySaveToolOutputSchema = ToolResultSummarySchema.extend({
|
|
1414
|
-
status:
|
|
1415
|
-
scope:
|
|
1416
|
-
indexed:
|
|
1034
|
+
status: z3.enum(["saved", "duplicate"]),
|
|
1035
|
+
scope: z3.enum(["gezel", "project"]),
|
|
1036
|
+
indexed: z3.boolean().optional()
|
|
1417
1037
|
});
|
|
1418
1038
|
var MemoryListToolOutputSchema = ToolResultSummarySchema.extend({
|
|
1419
|
-
scope:
|
|
1420
|
-
days:
|
|
1421
|
-
content:
|
|
1039
|
+
scope: z3.enum(["gezel", "project"]),
|
|
1040
|
+
days: z3.number().int().positive(),
|
|
1041
|
+
content: z3.string()
|
|
1422
1042
|
});
|
|
1423
1043
|
var ActionToolOutputSchema = ToolResultSummarySchema.extend({
|
|
1424
|
-
status:
|
|
1425
|
-
draftId:
|
|
1426
|
-
relPath:
|
|
1427
|
-
messageId:
|
|
1044
|
+
status: z3.string(),
|
|
1045
|
+
draftId: z3.string().optional(),
|
|
1046
|
+
relPath: z3.string().optional(),
|
|
1047
|
+
messageId: z3.string().optional()
|
|
1428
1048
|
});
|
|
1429
|
-
var BatchReadToolOutputSchema =
|
|
1430
|
-
results:
|
|
1431
|
-
|
|
1432
|
-
path:
|
|
1433
|
-
status:
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1049
|
+
var BatchReadToolOutputSchema = z3.object({
|
|
1050
|
+
results: z3.array(
|
|
1051
|
+
z3.object({
|
|
1052
|
+
path: z3.string(),
|
|
1053
|
+
status: z3.enum(["ok", "error"]),
|
|
1054
|
+
requestedPath: z3.string().optional(),
|
|
1055
|
+
resolvedPath: z3.string().optional(),
|
|
1056
|
+
resolvedSurface: z3.enum(["workspace", "artifact"]).optional(),
|
|
1057
|
+
rerouted: z3.boolean().optional(),
|
|
1058
|
+
fuzzy: z3.boolean().optional(),
|
|
1059
|
+
startLine: z3.number().int().positive().optional(),
|
|
1060
|
+
endLine: z3.number().int().nonnegative().optional(),
|
|
1061
|
+
completeFile: z3.boolean().optional(),
|
|
1062
|
+
code: z3.string().optional(),
|
|
1063
|
+
content: z3.string().optional(),
|
|
1064
|
+
totalLines: z3.number().int().nonnegative().optional(),
|
|
1065
|
+
hasMore: z3.boolean().optional(),
|
|
1066
|
+
nextStartLine: z3.number().int().positive().optional(),
|
|
1067
|
+
error: z3.string().optional()
|
|
1443
1068
|
})
|
|
1444
1069
|
)
|
|
1445
1070
|
});
|
|
1446
|
-
var EditToolOutputSchema =
|
|
1447
|
-
diff:
|
|
1448
|
-
addedLines:
|
|
1449
|
-
removedLines:
|
|
1450
|
-
diffTruncated:
|
|
1071
|
+
var EditToolOutputSchema = z3.object({
|
|
1072
|
+
diff: z3.string(),
|
|
1073
|
+
addedLines: z3.number().int().nonnegative(),
|
|
1074
|
+
removedLines: z3.number().int().nonnegative(),
|
|
1075
|
+
diffTruncated: z3.boolean().optional()
|
|
1451
1076
|
});
|
|
1452
|
-
var VideoToolOutputSchema =
|
|
1453
|
-
gezelVideo:
|
|
1454
|
-
artifactPath:
|
|
1455
|
-
mimeType:
|
|
1077
|
+
var VideoToolOutputSchema = z3.object({
|
|
1078
|
+
gezelVideo: z3.object({
|
|
1079
|
+
artifactPath: z3.string(),
|
|
1080
|
+
mimeType: z3.string()
|
|
1456
1081
|
})
|
|
1457
1082
|
});
|
|
1458
1083
|
var TOOL_OUTPUT_SCHEMAS = {
|
|
@@ -1475,6 +1100,7 @@ var TOOL_OUTPUT_SCHEMAS = {
|
|
|
1475
1100
|
list_dir: ListToolOutputSchema,
|
|
1476
1101
|
read_files: BatchReadToolOutputSchema,
|
|
1477
1102
|
list_artifacts: ListToolOutputSchema,
|
|
1103
|
+
read_artifacts: BatchReadToolOutputSchema,
|
|
1478
1104
|
list_documents: ListToolOutputSchema,
|
|
1479
1105
|
list_gezels: ListToolOutputSchema,
|
|
1480
1106
|
list_projects: ListToolOutputSchema,
|
|
@@ -1497,6 +1123,7 @@ var TOOL_OUTPUT_SCHEMAS = {
|
|
|
1497
1123
|
add_verification_step: TaskToolOutputSchema,
|
|
1498
1124
|
spawn_task_instances: TaskToolOutputSchema,
|
|
1499
1125
|
set_task_status: TaskToolOutputSchema,
|
|
1126
|
+
manage_task: TaskToolOutputSchema,
|
|
1500
1127
|
activate_task: TaskToolOutputSchema,
|
|
1501
1128
|
assign_task: TaskToolOutputSchema,
|
|
1502
1129
|
add_task_step: TaskToolOutputSchema,
|
|
@@ -1563,6 +1190,7 @@ var READ_ONLY_TOOLS = /* @__PURE__ */ new Set([
|
|
|
1563
1190
|
"list_packages",
|
|
1564
1191
|
"list_artifacts",
|
|
1565
1192
|
"read_artifact",
|
|
1193
|
+
"read_artifacts",
|
|
1566
1194
|
"grep_artifact",
|
|
1567
1195
|
"browser_find_page_element",
|
|
1568
1196
|
"list_documents",
|
|
@@ -1586,6 +1214,7 @@ var READ_ONLY_TOOLS = /* @__PURE__ */ new Set([
|
|
|
1586
1214
|
"fetch_url",
|
|
1587
1215
|
"web_search",
|
|
1588
1216
|
"wikipedia_search",
|
|
1217
|
+
"wikimedia_image_search",
|
|
1589
1218
|
"wikipedia_read",
|
|
1590
1219
|
"grep_files",
|
|
1591
1220
|
"find_files",
|
|
@@ -1720,6 +1349,7 @@ var OPEN_WORLD_TOOLS = /* @__PURE__ */ new Set([
|
|
|
1720
1349
|
"fetch_url",
|
|
1721
1350
|
"web_search",
|
|
1722
1351
|
"wikipedia_search",
|
|
1352
|
+
"wikimedia_image_search",
|
|
1723
1353
|
"wikipedia_read",
|
|
1724
1354
|
"github_pr_list",
|
|
1725
1355
|
"github_pr_view",
|
|
@@ -1752,14 +1382,1270 @@ function annotationsForTool(name) {
|
|
|
1752
1382
|
const readOnly = READ_ONLY_TOOLS.has(canonical);
|
|
1753
1383
|
if (!isKnown) return { ...UNKNOWN_TOOL_ANNOTATIONS };
|
|
1754
1384
|
return {
|
|
1755
|
-
readOnlyHint: readOnly,
|
|
1756
|
-
destructiveHint: readOnly ? false : !NON_DESTRUCTIVE_MUTATIONS.has(canonical),
|
|
1757
|
-
idempotentHint: readOnly || IDEMPOTENT_MUTATIONS.has(canonical),
|
|
1758
|
-
openWorldHint: OPEN_WORLD_TOOLS.has(canonical)
|
|
1385
|
+
readOnlyHint: readOnly,
|
|
1386
|
+
destructiveHint: readOnly ? false : !NON_DESTRUCTIVE_MUTATIONS.has(canonical),
|
|
1387
|
+
idempotentHint: readOnly || IDEMPOTENT_MUTATIONS.has(canonical),
|
|
1388
|
+
openWorldHint: OPEN_WORLD_TOOLS.has(canonical)
|
|
1389
|
+
};
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
// src/workspace-grep-result.ts
|
|
1393
|
+
function equivalentWorkspaceGrepArgs(path, pattern, options) {
|
|
1394
|
+
return {
|
|
1395
|
+
path,
|
|
1396
|
+
pattern,
|
|
1397
|
+
// grep_artifact defaults to insensitive while grep_files defaults to
|
|
1398
|
+
// sensitive, so this must be explicit for a truly equivalent retry.
|
|
1399
|
+
caseInsensitive: options.caseInsensitive ?? true,
|
|
1400
|
+
contextLines: Math.min(options.contextLines ?? 0, 5),
|
|
1401
|
+
maxResults: options.maxMatches ?? 20
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
function renderExactToolCall(name, args) {
|
|
1405
|
+
return `${name}(${JSON.stringify(args)})`;
|
|
1406
|
+
}
|
|
1407
|
+
function workspaceGrepResult(args, response, notice = "") {
|
|
1408
|
+
const prefix = notice ? `${notice}
|
|
1409
|
+
|
|
1410
|
+
` : "";
|
|
1411
|
+
const truncation = response.truncated ? `
|
|
1412
|
+
Results truncated (${response.truncationReason ?? "limit"}).${response.nextCursor !== void 0 ? ` Continue with cursor=${response.nextCursor}, or narrow path/includeGlobs/pattern.` : " Narrow path/includeGlobs/pattern."}` : "";
|
|
1413
|
+
if (response.mode === "count") {
|
|
1414
|
+
const qualifier = response.truncated ? "at least " : "";
|
|
1415
|
+
const summary = `${qualifier}${response.count} matching line${response.count === 1 ? "" : "s"} (engine=${response.engine}).`;
|
|
1416
|
+
return okResult(
|
|
1417
|
+
SearchToolOutputSchema,
|
|
1418
|
+
{
|
|
1419
|
+
summary,
|
|
1420
|
+
query: args.pattern,
|
|
1421
|
+
matches: [],
|
|
1422
|
+
count: response.count,
|
|
1423
|
+
truncated: response.truncated,
|
|
1424
|
+
engine: response.engine,
|
|
1425
|
+
mode: response.mode,
|
|
1426
|
+
...response.nextCursor !== void 0 ? { nextCursor: response.nextCursor } : {},
|
|
1427
|
+
...response.truncationReason ? { truncationReason: response.truncationReason } : {}
|
|
1428
|
+
},
|
|
1429
|
+
{ text: `${prefix}${summary}${truncation}` }
|
|
1430
|
+
);
|
|
1431
|
+
}
|
|
1432
|
+
if (response.mode === "files") {
|
|
1433
|
+
const header2 = `${response.files.length} matching file${response.files.length === 1 ? "" : "s"} (engine=${response.engine})`;
|
|
1434
|
+
return okResult(
|
|
1435
|
+
SearchToolOutputSchema,
|
|
1436
|
+
{
|
|
1437
|
+
summary: `${header2}.`,
|
|
1438
|
+
query: args.pattern,
|
|
1439
|
+
matches: response.files.map((path) => ({ path })),
|
|
1440
|
+
count: response.files.length,
|
|
1441
|
+
truncated: response.truncated,
|
|
1442
|
+
engine: response.engine,
|
|
1443
|
+
mode: response.mode,
|
|
1444
|
+
...response.nextCursor !== void 0 ? { nextCursor: response.nextCursor } : {},
|
|
1445
|
+
...response.truncationReason ? { truncationReason: response.truncationReason } : {}
|
|
1446
|
+
},
|
|
1447
|
+
{
|
|
1448
|
+
text: `${prefix}${header2}
|
|
1449
|
+
${response.files.join("\n") || "(none)"}${truncation}`
|
|
1450
|
+
}
|
|
1451
|
+
);
|
|
1452
|
+
}
|
|
1453
|
+
const lines = response.matches.flatMap((match, index) => {
|
|
1454
|
+
const block = [
|
|
1455
|
+
...(match.before ?? []).map((line) => `${match.path}-${line.line}-${line.text}`),
|
|
1456
|
+
`${match.path}:${match.line}:${match.text}`,
|
|
1457
|
+
...(match.after ?? []).map((line) => `${match.path}-${line.line}-${line.text}`)
|
|
1458
|
+
];
|
|
1459
|
+
if (index < response.matches.length - 1 && (match.before?.length || match.after?.length)) {
|
|
1460
|
+
block.push("--");
|
|
1461
|
+
}
|
|
1462
|
+
return block;
|
|
1463
|
+
});
|
|
1464
|
+
const header = `${response.matches.length} match${response.matches.length === 1 ? "" : "es"} (engine=${response.engine})`;
|
|
1465
|
+
return okResult(
|
|
1466
|
+
SearchToolOutputSchema,
|
|
1467
|
+
{
|
|
1468
|
+
summary: `${header}.`,
|
|
1469
|
+
query: args.pattern,
|
|
1470
|
+
matches: response.matches,
|
|
1471
|
+
count: response.matches.length,
|
|
1472
|
+
truncated: response.truncated,
|
|
1473
|
+
engine: response.engine,
|
|
1474
|
+
mode: response.mode,
|
|
1475
|
+
...response.nextCursor !== void 0 ? { nextCursor: response.nextCursor } : {},
|
|
1476
|
+
...response.truncationReason ? { truncationReason: response.truncationReason } : {}
|
|
1477
|
+
},
|
|
1478
|
+
{ text: `${prefix}${header}
|
|
1479
|
+
${lines.join("\n") || "(no matches)"}${truncation}` }
|
|
1480
|
+
);
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
// src/cross-drawer-read-tools.ts
|
|
1484
|
+
function workspaceReadRangeError(args) {
|
|
1485
|
+
const start = args.startLine ?? 1;
|
|
1486
|
+
if (args.endLine !== void 0 && args.endLine < start) {
|
|
1487
|
+
return `endLine (${args.endLine}) must be greater than or equal to startLine (${start})`;
|
|
1488
|
+
}
|
|
1489
|
+
if (args.endLine !== void 0 && args.endLine - start + 1 > WORKSPACE_READ_MAX_RANGE_LINES) {
|
|
1490
|
+
return `a read range may contain at most ${WORKSPACE_READ_MAX_RANGE_LINES} lines`;
|
|
1491
|
+
}
|
|
1492
|
+
return null;
|
|
1493
|
+
}
|
|
1494
|
+
function formatWorkspaceRead(result, raw) {
|
|
1495
|
+
const body = raw ? result.content : withLineNumbers(result.content, result.startLine);
|
|
1496
|
+
if (raw) return body;
|
|
1497
|
+
return `[read_file path=${JSON.stringify(result.path)} ${workspaceReadRangeLabel(result)}${result.completeFile ? " complete" : ""}]
|
|
1498
|
+
${body || "(no lines returned)"}${workspaceReadHint(result)}`;
|
|
1499
|
+
}
|
|
1500
|
+
function workspaceReadRangeLabel(result) {
|
|
1501
|
+
const total = result.totalLines === void 0 ? "?" : String(result.totalLines);
|
|
1502
|
+
if (result.linesReturned === 0) return `lines=none totalLines=${total}`;
|
|
1503
|
+
return `lines=${result.startLine}-${result.endLine} totalLines=${total}`;
|
|
1504
|
+
}
|
|
1505
|
+
function workspaceReadHint(result) {
|
|
1506
|
+
if (result.nextStartLine === void 0 && !result.truncated) return "";
|
|
1507
|
+
const parts = [];
|
|
1508
|
+
if (result.nextStartLine !== void 0) {
|
|
1509
|
+
const nextEnd = result.nextStartLine + WORKSPACE_READ_MAX_RANGE_LINES - 1;
|
|
1510
|
+
parts.push(
|
|
1511
|
+
`next: read_file({"path":${JSON.stringify(result.path)},"startLine":${result.nextStartLine},"endLine":${nextEnd}})`
|
|
1512
|
+
);
|
|
1513
|
+
}
|
|
1514
|
+
if (result.truncationReason) parts.push(`truncated=${result.truncationReason}`);
|
|
1515
|
+
return `
|
|
1516
|
+
|
|
1517
|
+
\u2026[${parts.join("; ")}]`;
|
|
1518
|
+
}
|
|
1519
|
+
async function artifactCollisionForWorkspacePath(dependencies, path) {
|
|
1520
|
+
try {
|
|
1521
|
+
if ((await dependencies.concreteWorkspaceTarget(path)).kind === "linked") return null;
|
|
1522
|
+
const cleanPath = dependencies.normalizeArtifactPath(path);
|
|
1523
|
+
const result = await dependencies.api.readProjectArtifactSlice(
|
|
1524
|
+
dependencies.projectId,
|
|
1525
|
+
cleanPath,
|
|
1526
|
+
{ head: 0 }
|
|
1527
|
+
);
|
|
1528
|
+
return result.kind === "found" && !result.fuzzy ? result.path : null;
|
|
1529
|
+
} catch {
|
|
1530
|
+
return null;
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
function artifactSliceArgsError(args) {
|
|
1534
|
+
const canonicalRange = args.startLine !== void 0 || args.endLine !== void 0;
|
|
1535
|
+
const modes = [
|
|
1536
|
+
canonicalRange,
|
|
1537
|
+
args.lines !== void 0,
|
|
1538
|
+
args.head !== void 0,
|
|
1539
|
+
args.tail !== void 0
|
|
1540
|
+
];
|
|
1541
|
+
if (modes.filter(Boolean).length > 1) {
|
|
1542
|
+
return "pass only one slice shape: startLine/endLine, lines, head, or tail";
|
|
1543
|
+
}
|
|
1544
|
+
if (canonicalRange) return workspaceReadRangeError(args);
|
|
1545
|
+
return null;
|
|
1546
|
+
}
|
|
1547
|
+
function artifactSliceOpts(args) {
|
|
1548
|
+
if (args.startLine !== void 0 || args.endLine !== void 0) {
|
|
1549
|
+
const start = args.startLine ?? 1;
|
|
1550
|
+
return {
|
|
1551
|
+
lines: {
|
|
1552
|
+
start,
|
|
1553
|
+
count: args.endLine === void 0 ? WORKSPACE_READ_MAX_RANGE_LINES : args.endLine - start + 1
|
|
1554
|
+
}
|
|
1555
|
+
};
|
|
1556
|
+
}
|
|
1557
|
+
if (args.lines) return { lines: args.lines };
|
|
1558
|
+
if (typeof args.head === "number") return { head: args.head };
|
|
1559
|
+
if (typeof args.tail === "number") return { tail: args.tail };
|
|
1560
|
+
return {};
|
|
1561
|
+
}
|
|
1562
|
+
function artifactSliceStart(args, totalLines, linesReturned) {
|
|
1563
|
+
if (args.startLine !== void 0) return args.startLine;
|
|
1564
|
+
if (args.lines) return args.lines.start;
|
|
1565
|
+
if (typeof args.tail === "number") return Math.max(1, totalLines - linesReturned + 1);
|
|
1566
|
+
return 1;
|
|
1567
|
+
}
|
|
1568
|
+
function reroutedReadNotice(requestedTool, resolvedTool, surface, path) {
|
|
1569
|
+
if (resolvedTool === "read_doc_as_markdown") {
|
|
1570
|
+
return `[Rerouted ${requestedTool} \u2192 read_doc_as_markdown]
|
|
1571
|
+
Opened ${JSON.stringify(path)} as a binary office document and converted it to markdown; reading it as text would have returned container bytes. Call read_doc_as_markdown directly for other documents.`;
|
|
1572
|
+
}
|
|
1573
|
+
return `[Rerouted ${requestedTool} \u2192 ${resolvedTool}]
|
|
1574
|
+
Opened ${surface} file ${JSON.stringify(path)}. Use ${surface === "artifact" ? "read_artifact/write_artifact" : "read_file/workspace write tools"} for subsequent operations on this path.`;
|
|
1575
|
+
}
|
|
1576
|
+
async function rerouteBinaryDocumentRead(dependencies, path, surface) {
|
|
1577
|
+
const { api: api2, projectId: projectId2, toolIsAuthorized, unwrapApiError: unwrapApiError2 } = dependencies;
|
|
1578
|
+
if (!isBinaryDocumentPath2(path)) return null;
|
|
1579
|
+
const artifact = surface === "artifact";
|
|
1580
|
+
const requestedTool = artifact ? "read_artifact" : "read_file";
|
|
1581
|
+
const exactCall = renderExactToolCall("read_doc_as_markdown", {
|
|
1582
|
+
path,
|
|
1583
|
+
...artifact ? { artifact: true } : {}
|
|
1584
|
+
});
|
|
1585
|
+
if (!toolIsAuthorized("read_doc_as_markdown")) {
|
|
1586
|
+
const kind = binaryDocumentExtension2(path)?.toUpperCase() ?? "office";
|
|
1587
|
+
return {
|
|
1588
|
+
content: [
|
|
1589
|
+
{
|
|
1590
|
+
type: "text",
|
|
1591
|
+
text: `${requestedTool} "${path}": this is a binary ${kind} document, not text. Reading it as text returns container bytes, not its content. \`read_doc_as_markdown\` is not authorized for this session \u2014 hand this source to a gezel that has it (${exactCall}).`
|
|
1592
|
+
}
|
|
1593
|
+
]
|
|
1594
|
+
};
|
|
1595
|
+
}
|
|
1596
|
+
try {
|
|
1597
|
+
const res = await api2.toolReadDocAsMarkdown(projectId2, {
|
|
1598
|
+
path,
|
|
1599
|
+
...artifact ? { artifact: true } : {}
|
|
1600
|
+
});
|
|
1601
|
+
if (!res.found) return null;
|
|
1602
|
+
const notice = reroutedReadNotice(requestedTool, "read_doc_as_markdown", surface, path);
|
|
1603
|
+
const head = `${res.sourcePath} \u2192 ${res.markdownPath}${res.truncated ? " (truncated)" : ""}`;
|
|
1604
|
+
return {
|
|
1605
|
+
content: [
|
|
1606
|
+
{ type: "text", text: `${notice}
|
|
1607
|
+
|
|
1608
|
+
${head}
|
|
1609
|
+
---
|
|
1610
|
+
${res.markdown ?? ""}` }
|
|
1611
|
+
],
|
|
1612
|
+
structuredContent: {
|
|
1613
|
+
requestedTool,
|
|
1614
|
+
requestedPath: path,
|
|
1615
|
+
resolvedTool: "read_doc_as_markdown",
|
|
1616
|
+
resolvedSurface: surface,
|
|
1617
|
+
resolvedPath: res.sourcePath,
|
|
1618
|
+
rerouted: true,
|
|
1619
|
+
content: res.markdown ?? "",
|
|
1620
|
+
truncated: res.truncated ?? false
|
|
1621
|
+
}
|
|
1622
|
+
};
|
|
1623
|
+
} catch (error) {
|
|
1624
|
+
void unwrapApiError2(error);
|
|
1625
|
+
return null;
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
function registerWorkspaceReadTools(dependencies) {
|
|
1629
|
+
const {
|
|
1630
|
+
server: server2,
|
|
1631
|
+
api: api2,
|
|
1632
|
+
projectId: projectId2,
|
|
1633
|
+
readWorkspaceFile: readWorkspaceFile2,
|
|
1634
|
+
readWorkspaceFiles: readWorkspaceFiles2,
|
|
1635
|
+
concreteWorkspaceTarget: concreteWorkspaceTarget2,
|
|
1636
|
+
workspaceClient: workspaceClient2,
|
|
1637
|
+
toolIsAuthorized,
|
|
1638
|
+
unwrapApiError: unwrapApiError2
|
|
1639
|
+
} = dependencies;
|
|
1640
|
+
server2.tool(
|
|
1641
|
+
"read_file",
|
|
1642
|
+
"Read one project-workspace file, optionally only an inclusive line range. This tool never reads the separate artifacts drawer; use read_artifact for artifact inputs. For files over ~200 lines, pass `startLine`/`endLine` from grep_files, outline_file, or an error instead of loading the whole file. Omit both range fields for the backward-compatible full read. Output uses `N\u2192` line gutters for precise edits; the gutter is display-only and is never part of the file. Pass `raw: true` for text without gutters.",
|
|
1643
|
+
ReadFileInputSchema.extend({
|
|
1644
|
+
endLine: z4.number().int().min(1).max(1e7).optional().describe(
|
|
1645
|
+
`1-based last line to return (inclusive). Maximum ${WORKSPACE_READ_MAX_RANGE_LINES} lines per ranged read; omit to read the next bounded chunk.`
|
|
1646
|
+
)
|
|
1647
|
+
}).shape,
|
|
1648
|
+
async ({ path, startLine, endLine, raw }) => {
|
|
1649
|
+
try {
|
|
1650
|
+
const rerouted = await rerouteBinaryDocumentRead(dependencies, path, "workspace");
|
|
1651
|
+
if (rerouted) return rerouted;
|
|
1652
|
+
const rangeError = workspaceReadRangeError({ startLine, endLine });
|
|
1653
|
+
if (rangeError) throw new Error(rangeError);
|
|
1654
|
+
if (raw && (startLine !== void 0 || endLine !== void 0)) {
|
|
1655
|
+
throw new Error(
|
|
1656
|
+
"`raw: true` cannot be combined with a line range; omit `raw` for a numbered range"
|
|
1657
|
+
);
|
|
1658
|
+
}
|
|
1659
|
+
if (startLine === void 0 && endLine === void 0) {
|
|
1660
|
+
const result2 = await readWorkspaceFile2(path);
|
|
1661
|
+
return {
|
|
1662
|
+
content: [
|
|
1663
|
+
{
|
|
1664
|
+
type: "text",
|
|
1665
|
+
text: raw ? result2.content : withLineNumbers(result2.content)
|
|
1666
|
+
}
|
|
1667
|
+
]
|
|
1668
|
+
};
|
|
1669
|
+
}
|
|
1670
|
+
const response = await readWorkspaceFiles2([
|
|
1671
|
+
{
|
|
1672
|
+
path,
|
|
1673
|
+
...startLine !== void 0 ? { startLine } : {},
|
|
1674
|
+
...endLine !== void 0 ? { endLine } : {}
|
|
1675
|
+
}
|
|
1676
|
+
]);
|
|
1677
|
+
const result = response.results[0];
|
|
1678
|
+
if (!result) throw new Error("ranged read returned no result");
|
|
1679
|
+
if (result.status === "error") throw new Error(`[${result.code}] ${result.error}`);
|
|
1680
|
+
return {
|
|
1681
|
+
content: [{ type: "text", text: formatWorkspaceRead(result, raw === true) }]
|
|
1682
|
+
};
|
|
1683
|
+
} catch (error) {
|
|
1684
|
+
const base = unwrapApiError2(error);
|
|
1685
|
+
let text = `read_file "${path}": ${base}`;
|
|
1686
|
+
if (/not found|404|no such file/i.test(base)) {
|
|
1687
|
+
const artifactCollision = await artifactCollisionForWorkspacePath(dependencies, path);
|
|
1688
|
+
if (artifactCollision) {
|
|
1689
|
+
const exactCall = renderExactToolCall("read_artifact", {
|
|
1690
|
+
path: artifactCollision,
|
|
1691
|
+
...startLine !== void 0 ? { startLine } : {},
|
|
1692
|
+
...endLine !== void 0 ? { endLine } : {}
|
|
1693
|
+
});
|
|
1694
|
+
if (!toolIsAuthorized("read_artifact")) {
|
|
1695
|
+
text += `. A project artifact exists at "${artifactCollision}", but read_artifact is not authorized for this session.`;
|
|
1696
|
+
return errorResult(text, {
|
|
1697
|
+
retryable: false,
|
|
1698
|
+
hint: `Delegate to a gezel with artifact read access to run ${exactCall}`
|
|
1699
|
+
});
|
|
1700
|
+
}
|
|
1701
|
+
try {
|
|
1702
|
+
const artifact = await api2.readProjectArtifactSlice(
|
|
1703
|
+
projectId2,
|
|
1704
|
+
artifactCollision,
|
|
1705
|
+
artifactSliceOpts({ startLine, endLine })
|
|
1706
|
+
);
|
|
1707
|
+
if (artifact.kind === "found" && !artifact.fuzzy) {
|
|
1708
|
+
const sliceStart = artifactSliceStart(
|
|
1709
|
+
{ startLine, endLine },
|
|
1710
|
+
artifact.totalLines,
|
|
1711
|
+
artifact.linesReturned
|
|
1712
|
+
);
|
|
1713
|
+
const body = raw ? artifact.content : withLineNumbers(artifact.content, sliceStart) || "(no lines returned)";
|
|
1714
|
+
const notice = reroutedReadNotice(
|
|
1715
|
+
"read_file",
|
|
1716
|
+
"read_artifact",
|
|
1717
|
+
"artifact",
|
|
1718
|
+
artifact.path
|
|
1719
|
+
);
|
|
1720
|
+
return {
|
|
1721
|
+
content: [{ type: "text", text: `${notice}
|
|
1722
|
+
|
|
1723
|
+
${body}` }],
|
|
1724
|
+
structuredContent: {
|
|
1725
|
+
requestedTool: "read_file",
|
|
1726
|
+
requestedPath: path,
|
|
1727
|
+
resolvedTool: "read_artifact",
|
|
1728
|
+
resolvedSurface: "artifact",
|
|
1729
|
+
resolvedPath: artifact.path,
|
|
1730
|
+
rerouted: true,
|
|
1731
|
+
content: artifact.content,
|
|
1732
|
+
startLine: sliceStart,
|
|
1733
|
+
endLine: sliceStart + Math.max(0, artifact.linesReturned - 1),
|
|
1734
|
+
totalLines: artifact.totalLines,
|
|
1735
|
+
hasMore: artifact.hasMore
|
|
1736
|
+
}
|
|
1737
|
+
};
|
|
1738
|
+
}
|
|
1739
|
+
} catch (fallbackError) {
|
|
1740
|
+
return errorResult(
|
|
1741
|
+
`${text}. The automatic artifact fallback failed: ${unwrapApiError2(fallbackError)}`,
|
|
1742
|
+
{ retryable: true, hint: exactCall }
|
|
1743
|
+
);
|
|
1744
|
+
}
|
|
1745
|
+
return errorResult(`${text}. The artifact disappeared before it could be opened.`, {
|
|
1746
|
+
retryable: true,
|
|
1747
|
+
hint: exactCall
|
|
1748
|
+
});
|
|
1749
|
+
}
|
|
1750
|
+
try {
|
|
1751
|
+
const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
|
|
1752
|
+
const targetDir = await concreteWorkspaceTarget2(dir);
|
|
1753
|
+
const listing = await workspaceClient2(targetDir).listProjectWorkspace(
|
|
1754
|
+
targetDir.projectId,
|
|
1755
|
+
targetDir.path,
|
|
1756
|
+
false
|
|
1757
|
+
);
|
|
1758
|
+
const names = listing.files.filter((file) => !file.isDirectory).map((file) => file.path.split("/").pop() ?? file.path);
|
|
1759
|
+
const target = path.split("/").pop() ?? path;
|
|
1760
|
+
const near = closestFileNames(target, names);
|
|
1761
|
+
const where = dir === "" ? "the project root" : `${dir}/`;
|
|
1762
|
+
if (near.length > 0) {
|
|
1763
|
+
text += `. Nearest existing in ${where}: ${near.join(", ")}`;
|
|
1764
|
+
} else if (names.length > 0) {
|
|
1765
|
+
text += `. ${where} contains: ${names.slice(0, 10).join(", ")}${names.length > 10 ? ", \u2026" : ""}`;
|
|
1766
|
+
}
|
|
1767
|
+
} catch {
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
return { content: [{ type: "text", text }], isError: true };
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
);
|
|
1774
|
+
server2.tool(
|
|
1775
|
+
"read_files",
|
|
1776
|
+
`Read up to ${WORKSPACE_READ_MAX_FILES} known workspace files or line ranges in one call. Pass simple \`paths\` for whole-file first chunks, or richer \`files\` entries with inclusive startLine/endLine ranges; pass exactly one of those fields. Use this for independent files you already identified and grep_files/find_files first when paths are unknown. Results stay in request order and report item-level errors without discarding successful reads.`,
|
|
1777
|
+
{
|
|
1778
|
+
files: z4.array(
|
|
1779
|
+
z4.object({
|
|
1780
|
+
path: z4.string().min(1).max(4096).describe("Workspace-relative file path."),
|
|
1781
|
+
startLine: z4.number().int().min(1).max(1e7).optional().describe("1-based first line to return (inclusive). Defaults to 1."),
|
|
1782
|
+
endLine: z4.number().int().min(1).max(1e7).optional().describe(
|
|
1783
|
+
`1-based last line to return (inclusive); at most ${WORKSPACE_READ_MAX_RANGE_LINES} lines.`
|
|
1784
|
+
)
|
|
1785
|
+
})
|
|
1786
|
+
).min(1).max(WORKSPACE_READ_MAX_FILES).optional().describe("Files/ranges to read, in the order their results should be returned."),
|
|
1787
|
+
paths: z4.array(z4.string().min(1).max(4096)).min(1).max(WORKSPACE_READ_MAX_FILES).optional().describe(
|
|
1788
|
+
"Simple workspace-relative paths. Use `files` instead when any path needs a range."
|
|
1789
|
+
)
|
|
1790
|
+
},
|
|
1791
|
+
async ({ files, paths }) => {
|
|
1792
|
+
try {
|
|
1793
|
+
if (files === void 0 === (paths === void 0)) {
|
|
1794
|
+
throw new Error("pass exactly one of `paths` or `files`");
|
|
1795
|
+
}
|
|
1796
|
+
const requests = files ?? paths?.map((path) => ({ path })) ?? [];
|
|
1797
|
+
for (const request of requests) {
|
|
1798
|
+
const rangeError = workspaceReadRangeError(request);
|
|
1799
|
+
if (rangeError) throw new Error(`${request.path}: ${rangeError}`);
|
|
1800
|
+
}
|
|
1801
|
+
const response = await readWorkspaceFiles2(requests);
|
|
1802
|
+
const results = await Promise.all(
|
|
1803
|
+
response.results.map(async (result, index2) => {
|
|
1804
|
+
if (result.status !== "error" || result.code !== "path-not-found") {
|
|
1805
|
+
return { ...result, resolvedSurface: "workspace", rerouted: false };
|
|
1806
|
+
}
|
|
1807
|
+
const request = requests[index2];
|
|
1808
|
+
const collision = await artifactCollisionForWorkspacePath(dependencies, request.path);
|
|
1809
|
+
if (!collision) {
|
|
1810
|
+
return { ...result, resolvedSurface: "workspace", rerouted: false };
|
|
1811
|
+
}
|
|
1812
|
+
if (!toolIsAuthorized("read_artifact")) {
|
|
1813
|
+
return {
|
|
1814
|
+
status: "error",
|
|
1815
|
+
path: request.path,
|
|
1816
|
+
code: "artifact-read-unauthorized",
|
|
1817
|
+
error: `${result.error}. An artifact exists at "${collision}", but read_artifact is not authorized for this session.`,
|
|
1818
|
+
requestedPath: request.path,
|
|
1819
|
+
resolvedPath: collision,
|
|
1820
|
+
resolvedSurface: "artifact",
|
|
1821
|
+
rerouted: false
|
|
1822
|
+
};
|
|
1823
|
+
}
|
|
1824
|
+
try {
|
|
1825
|
+
const artifact = await api2.readProjectArtifactSlice(
|
|
1826
|
+
projectId2,
|
|
1827
|
+
collision,
|
|
1828
|
+
artifactSliceOpts(request)
|
|
1829
|
+
);
|
|
1830
|
+
if (artifact.kind !== "found" || artifact.fuzzy) {
|
|
1831
|
+
return {
|
|
1832
|
+
...result,
|
|
1833
|
+
resolvedSurface: "workspace",
|
|
1834
|
+
rerouted: false
|
|
1835
|
+
};
|
|
1836
|
+
}
|
|
1837
|
+
const start = artifactSliceStart(
|
|
1838
|
+
request,
|
|
1839
|
+
artifact.totalLines,
|
|
1840
|
+
artifact.linesReturned
|
|
1841
|
+
);
|
|
1842
|
+
const end = start + Math.max(0, artifact.linesReturned - 1);
|
|
1843
|
+
return {
|
|
1844
|
+
status: "ok",
|
|
1845
|
+
path: request.path,
|
|
1846
|
+
content: artifact.content,
|
|
1847
|
+
startLine: start,
|
|
1848
|
+
endLine: end,
|
|
1849
|
+
linesReturned: artifact.linesReturned,
|
|
1850
|
+
bytesReturned: artifact.bytesReturned,
|
|
1851
|
+
scannedBytes: artifact.totalBytes,
|
|
1852
|
+
totalLines: artifact.totalLines,
|
|
1853
|
+
totalBytes: artifact.totalBytes,
|
|
1854
|
+
eof: !artifact.hasMore,
|
|
1855
|
+
completeFile: artifact.linesReturned === artifact.totalLines,
|
|
1856
|
+
hasMore: artifact.hasMore,
|
|
1857
|
+
...artifact.hasMore ? { nextStartLine: end + 1 } : {},
|
|
1858
|
+
truncated: artifact.hasMore,
|
|
1859
|
+
...artifact.hasMore ? { truncationReason: "line-limit" } : {},
|
|
1860
|
+
requestedPath: request.path,
|
|
1861
|
+
resolvedPath: artifact.path,
|
|
1862
|
+
resolvedSurface: "artifact",
|
|
1863
|
+
rerouted: true
|
|
1864
|
+
};
|
|
1865
|
+
} catch (fallbackError) {
|
|
1866
|
+
return {
|
|
1867
|
+
...result,
|
|
1868
|
+
error: `${result.error}. Automatic artifact fallback failed: ${unwrapApiError2(fallbackError)}`,
|
|
1869
|
+
resolvedSurface: "workspace",
|
|
1870
|
+
rerouted: false
|
|
1871
|
+
};
|
|
1872
|
+
}
|
|
1873
|
+
})
|
|
1874
|
+
);
|
|
1875
|
+
const index = results.map((result, index2) => {
|
|
1876
|
+
if (result.status === "error") {
|
|
1877
|
+
return `${index2 + 1} ERROR ${result.path} [${result.code}] ${result.error}`;
|
|
1878
|
+
}
|
|
1879
|
+
const next = result.nextStartLine ? ` nextStartLine=${result.nextStartLine}` : "";
|
|
1880
|
+
const route = result.rerouted ? ` rerouted=artifact:${result.resolvedPath}` : "";
|
|
1881
|
+
return `${index2 + 1} OK ${result.path} ${workspaceReadRangeLabel(result)}${result.completeFile ? " complete" : ""}${next}${route}`;
|
|
1882
|
+
});
|
|
1883
|
+
const sections = results.map((result) => {
|
|
1884
|
+
if (result.status === "error") {
|
|
1885
|
+
return `--- ${result.path} [ERROR: ${result.code}] ---
|
|
1886
|
+
${result.error}`;
|
|
1887
|
+
}
|
|
1888
|
+
const range = workspaceReadRangeLabel(result);
|
|
1889
|
+
const body = withLineNumbers(result.content, result.startLine) || "(no lines returned)";
|
|
1890
|
+
const hint = workspaceReadHint(result);
|
|
1891
|
+
const notice = result.rerouted ? `${reroutedReadNotice("read_files", "read_artifact", "artifact", result.resolvedPath)}
|
|
1892
|
+
` : "";
|
|
1893
|
+
return `--- ${result.path} (${range}) ---
|
|
1894
|
+
${notice}${body}${hint}`;
|
|
1895
|
+
});
|
|
1896
|
+
const allFailed = results.length > 0 && results.every((result) => result.status === "error");
|
|
1897
|
+
return {
|
|
1898
|
+
content: [
|
|
1899
|
+
{
|
|
1900
|
+
type: "text",
|
|
1901
|
+
text: `[read_files requested=${results.length} ok=${results.filter((result) => result.status === "ok").length} errors=${results.filter((result) => result.status === "error").length}]
|
|
1902
|
+
${index.join("\n")}
|
|
1903
|
+
|
|
1904
|
+
${sections.join("\n\n")}`
|
|
1905
|
+
}
|
|
1906
|
+
],
|
|
1907
|
+
structuredContent: {
|
|
1908
|
+
results: results.map(
|
|
1909
|
+
(result) => result.status === "ok" ? {
|
|
1910
|
+
path: result.path,
|
|
1911
|
+
status: result.status,
|
|
1912
|
+
content: result.content,
|
|
1913
|
+
startLine: result.startLine,
|
|
1914
|
+
endLine: result.endLine,
|
|
1915
|
+
completeFile: result.completeFile,
|
|
1916
|
+
totalLines: result.totalLines,
|
|
1917
|
+
hasMore: result.hasMore,
|
|
1918
|
+
nextStartLine: result.nextStartLine,
|
|
1919
|
+
resolvedSurface: result.resolvedSurface,
|
|
1920
|
+
rerouted: result.rerouted,
|
|
1921
|
+
..."resolvedPath" in result ? { resolvedPath: result.resolvedPath } : {}
|
|
1922
|
+
} : {
|
|
1923
|
+
path: result.path,
|
|
1924
|
+
status: result.status,
|
|
1925
|
+
code: result.code,
|
|
1926
|
+
error: result.error,
|
|
1927
|
+
..."requestedPath" in result ? { requestedPath: result.requestedPath } : {},
|
|
1928
|
+
..."resolvedPath" in result ? { resolvedPath: result.resolvedPath } : {},
|
|
1929
|
+
resolvedSurface: result.resolvedSurface,
|
|
1930
|
+
rerouted: result.rerouted
|
|
1931
|
+
}
|
|
1932
|
+
)
|
|
1933
|
+
},
|
|
1934
|
+
...allFailed ? { isError: true } : {}
|
|
1935
|
+
};
|
|
1936
|
+
} catch (error) {
|
|
1937
|
+
return {
|
|
1938
|
+
content: [{ type: "text", text: `read_files failed: ${unwrapApiError2(error)}` }],
|
|
1939
|
+
isError: true
|
|
1940
|
+
};
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
);
|
|
1944
|
+
}
|
|
1945
|
+
function registerArtifactReadTools(dependencies) {
|
|
1946
|
+
const {
|
|
1947
|
+
server: server2,
|
|
1948
|
+
api: api2,
|
|
1949
|
+
projectId: projectId2,
|
|
1950
|
+
readWorkspaceFile: readWorkspaceFile2,
|
|
1951
|
+
readWorkspaceFiles: readWorkspaceFiles2,
|
|
1952
|
+
normalizeArtifactPath: normalizeArtifactPath2,
|
|
1953
|
+
workspaceCollisionForArtifactPath: workspaceCollisionForArtifactPath2,
|
|
1954
|
+
toolIsAuthorized,
|
|
1955
|
+
unwrapApiError: unwrapApiError2
|
|
1956
|
+
} = dependencies;
|
|
1957
|
+
server2.tool(
|
|
1958
|
+
"read_artifact",
|
|
1959
|
+
'Read one artifact, using a path returned by `list_artifacts`. Paths are relative to the artifact root: use "reports/summary.md", never add "artifacts/" (a legacy redundant prefix is still accepted). Use the same inclusive `startLine`/`endLine` range shape as `read_file`; the older `lines`/`head`/`tail` shapes remain accepted for compatibility. If the exact path is actually a workspace file and `read_file` is authorized, this read is safely rerouted and reports its resolved surface. Use `read_artifacts` for several known artifact paths.',
|
|
1960
|
+
ReadArtifactInputSchema.extend({
|
|
1961
|
+
endLine: z4.number().int().min(1).max(1e7).optional().describe(
|
|
1962
|
+
`Canonical 1-based last line to return (inclusive); at most ${WORKSPACE_READ_MAX_RANGE_LINES} lines.`
|
|
1963
|
+
),
|
|
1964
|
+
lines: z4.object({
|
|
1965
|
+
start: z4.number().int().min(1).describe("1-indexed first line to return."),
|
|
1966
|
+
count: z4.number().int().min(0).describe("Number of lines to return.")
|
|
1967
|
+
}).optional().describe("Legacy range shape; prefer `startLine` / `endLine`."),
|
|
1968
|
+
head: z4.number().int().min(0).optional().describe("Legacy: read just the first N lines."),
|
|
1969
|
+
tail: z4.number().int().min(0).optional().describe("Legacy: read just the last N lines.")
|
|
1970
|
+
}).shape,
|
|
1971
|
+
async ({ path, startLine, endLine, lines, head, tail }) => {
|
|
1972
|
+
const sliceArgs = { startLine, endLine, lines, head, tail };
|
|
1973
|
+
const sliceError = artifactSliceArgsError(sliceArgs);
|
|
1974
|
+
if (sliceError) return errorResult(`read_artifact "${path}": ${sliceError}`);
|
|
1975
|
+
const opts = artifactSliceOpts(sliceArgs);
|
|
1976
|
+
const clean = normalizeArtifactPath2(path);
|
|
1977
|
+
const rerouted = await rerouteBinaryDocumentRead(dependencies, clean, "artifact");
|
|
1978
|
+
if (rerouted) return rerouted;
|
|
1979
|
+
const result = await api2.readProjectArtifactSlice(projectId2, clean, opts);
|
|
1980
|
+
if (result.kind === "missing") {
|
|
1981
|
+
const workspaceCollision = await workspaceCollisionForArtifactPath2(clean);
|
|
1982
|
+
if (workspaceCollision) {
|
|
1983
|
+
const tool = workspaceCollision.kind === "dir" ? "list_dir" : "read_file";
|
|
1984
|
+
const exactCall = renderExactToolCall(tool, { path: workspaceCollision.path });
|
|
1985
|
+
if (workspaceCollision.kind === "dir" || !toolIsAuthorized("read_file")) {
|
|
1986
|
+
return errorResult(
|
|
1987
|
+
`Artifact "${path}" not found, but a workspace ${workspaceCollision.kind} exists at "${workspaceCollision.path}". ${tool} is not authorized for this session or cannot be safely substituted for this request.`,
|
|
1988
|
+
{
|
|
1989
|
+
retryable: false,
|
|
1990
|
+
hint: `Delegate to a gezel with workspace access to run ${exactCall}`
|
|
1991
|
+
}
|
|
1992
|
+
);
|
|
1993
|
+
}
|
|
1994
|
+
try {
|
|
1995
|
+
let content;
|
|
1996
|
+
let firstLine = 1;
|
|
1997
|
+
let totalLines;
|
|
1998
|
+
let hasMore = false;
|
|
1999
|
+
const emptySliceRequested = head === 0 || tail === 0 || lines !== void 0 && lines.count === 0;
|
|
2000
|
+
if (emptySliceRequested) {
|
|
2001
|
+
const workspace = await readWorkspaceFile2(workspaceCollision.path);
|
|
2002
|
+
totalLines = workspace.content.split("\n").length;
|
|
2003
|
+
content = "";
|
|
2004
|
+
firstLine = lines?.start ?? (tail === 0 ? totalLines + 1 : 1);
|
|
2005
|
+
hasMore = totalLines > 0;
|
|
2006
|
+
} else if (typeof tail === "number") {
|
|
2007
|
+
const workspace = await readWorkspaceFile2(workspaceCollision.path);
|
|
2008
|
+
const allLines = workspace.content.split("\n");
|
|
2009
|
+
const selected = allLines.slice(Math.max(0, allLines.length - tail));
|
|
2010
|
+
content = selected.join("\n");
|
|
2011
|
+
firstLine = Math.max(1, allLines.length - selected.length + 1);
|
|
2012
|
+
totalLines = allLines.length;
|
|
2013
|
+
hasMore = selected.length < allLines.length;
|
|
2014
|
+
} else {
|
|
2015
|
+
const request = lines ? {
|
|
2016
|
+
path: workspaceCollision.path,
|
|
2017
|
+
startLine: lines.start,
|
|
2018
|
+
endLine: lines.start + Math.max(0, lines.count - 1)
|
|
2019
|
+
} : typeof head === "number" ? { path: workspaceCollision.path, startLine: 1, endLine: Math.max(1, head) } : startLine !== void 0 || endLine !== void 0 ? {
|
|
2020
|
+
path: workspaceCollision.path,
|
|
2021
|
+
...startLine !== void 0 ? { startLine } : {},
|
|
2022
|
+
...endLine !== void 0 ? { endLine } : {}
|
|
2023
|
+
} : { path: workspaceCollision.path };
|
|
2024
|
+
if (request.startLine === void 0 && request.endLine === void 0) {
|
|
2025
|
+
const workspace = await readWorkspaceFile2(workspaceCollision.path);
|
|
2026
|
+
content = workspace.content;
|
|
2027
|
+
totalLines = content.split("\n").length;
|
|
2028
|
+
} else {
|
|
2029
|
+
const workspace = (await readWorkspaceFiles2([request])).results[0];
|
|
2030
|
+
if (!workspace || workspace.status === "error") {
|
|
2031
|
+
throw new Error(
|
|
2032
|
+
workspace?.status === "error" ? workspace.error : "workspace read returned no result"
|
|
2033
|
+
);
|
|
2034
|
+
}
|
|
2035
|
+
content = workspace.content;
|
|
2036
|
+
firstLine = workspace.startLine;
|
|
2037
|
+
totalLines = workspace.totalLines;
|
|
2038
|
+
hasMore = workspace.hasMore;
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
const notice = reroutedReadNotice(
|
|
2042
|
+
"read_artifact",
|
|
2043
|
+
"read_file",
|
|
2044
|
+
"workspace",
|
|
2045
|
+
workspaceCollision.path
|
|
2046
|
+
);
|
|
2047
|
+
return {
|
|
2048
|
+
content: [{ type: "text", text: `${notice}
|
|
2049
|
+
|
|
2050
|
+
${content}` }],
|
|
2051
|
+
structuredContent: {
|
|
2052
|
+
requestedTool: "read_artifact",
|
|
2053
|
+
requestedPath: path,
|
|
2054
|
+
resolvedTool: "read_file",
|
|
2055
|
+
resolvedSurface: "workspace",
|
|
2056
|
+
resolvedPath: workspaceCollision.path,
|
|
2057
|
+
rerouted: true,
|
|
2058
|
+
content,
|
|
2059
|
+
startLine: firstLine,
|
|
2060
|
+
...totalLines !== void 0 ? { totalLines } : {},
|
|
2061
|
+
hasMore
|
|
2062
|
+
}
|
|
2063
|
+
};
|
|
2064
|
+
} catch (fallbackError) {
|
|
2065
|
+
return errorResult(
|
|
2066
|
+
`Artifact "${path}" was not found and its automatic workspace fallback failed: ${unwrapApiError2(fallbackError)}`,
|
|
2067
|
+
{ retryable: true, hint: exactCall }
|
|
2068
|
+
);
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
return {
|
|
2072
|
+
content: [
|
|
2073
|
+
{
|
|
2074
|
+
type: "text",
|
|
2075
|
+
text: `Artifact "${path}" not found. Call list_artifacts to see what's available.`
|
|
2076
|
+
}
|
|
2077
|
+
],
|
|
2078
|
+
isError: true
|
|
2079
|
+
};
|
|
2080
|
+
}
|
|
2081
|
+
if (result.kind === "ambiguous") {
|
|
2082
|
+
return {
|
|
2083
|
+
content: [
|
|
2084
|
+
{
|
|
2085
|
+
type: "text",
|
|
2086
|
+
text: `"${path}" matches multiple artifacts. Call read_artifact again with a full path:
|
|
2087
|
+
${result.candidates.map((candidate) => ` \u2022 ${candidate}`).join("\n")}`
|
|
2088
|
+
}
|
|
2089
|
+
],
|
|
2090
|
+
isError: true
|
|
2091
|
+
};
|
|
2092
|
+
}
|
|
2093
|
+
const header = result.fuzzy ? `(matched ${result.path} by basename)
|
|
2094
|
+
` : "";
|
|
2095
|
+
const sliceStart = artifactSliceStart(sliceArgs, result.totalLines, result.linesReturned);
|
|
2096
|
+
const sliceEnd = sliceStart + Math.max(0, result.linesReturned - 1);
|
|
2097
|
+
const emptyRequested = head === 0 || tail === 0 || lines?.count === 0;
|
|
2098
|
+
const beyondEnd = !emptyRequested && result.linesReturned === 0 && sliceStart > result.totalLines;
|
|
2099
|
+
let sliceTail = "";
|
|
2100
|
+
if (beyondEnd) {
|
|
2101
|
+
sliceTail = `
|
|
2102
|
+
|
|
2103
|
+
[End of file: ${result.totalLines} total lines. No lines exist at or after requested startLine ${sliceStart}; do not page further.]`;
|
|
2104
|
+
} else if (emptyRequested) {
|
|
2105
|
+
sliceTail = `
|
|
2106
|
+
|
|
2107
|
+
[No lines requested; file has ${result.totalLines} total lines.]`;
|
|
2108
|
+
} else if (result.linesReturned !== result.totalLines) {
|
|
2109
|
+
const earlier = sliceStart > 1 ? " Earlier lines are not included in this slice." : "";
|
|
2110
|
+
const nextStart = sliceEnd + 1;
|
|
2111
|
+
const continuation = nextStart <= result.totalLines ? ` Next: ${renderExactToolCall("read_artifact", { path: result.path, startLine: nextStart, endLine: Math.min(result.totalLines, nextStart + WORKSPACE_READ_MAX_RANGE_LINES - 1) })}` : " End of file; no later lines.";
|
|
2112
|
+
sliceTail = `
|
|
2113
|
+
|
|
2114
|
+
[lines ${sliceStart}-${sliceEnd} of ${result.totalLines}.${earlier}${continuation}]`;
|
|
2115
|
+
}
|
|
2116
|
+
return {
|
|
2117
|
+
content: [{ type: "text", text: header + result.content + sliceTail }],
|
|
2118
|
+
structuredContent: {
|
|
2119
|
+
requestedPath: clean,
|
|
2120
|
+
resolvedPath: result.path,
|
|
2121
|
+
fuzzy: result.fuzzy,
|
|
2122
|
+
content: result.content,
|
|
2123
|
+
startLine: sliceStart,
|
|
2124
|
+
endLine: sliceEnd,
|
|
2125
|
+
linesReturned: result.linesReturned,
|
|
2126
|
+
totalLines: result.totalLines,
|
|
2127
|
+
hasMore: emptyRequested ? result.totalLines > 0 : !beyondEnd && sliceEnd < result.totalLines
|
|
2128
|
+
}
|
|
2129
|
+
};
|
|
2130
|
+
}
|
|
2131
|
+
);
|
|
2132
|
+
server2.tool(
|
|
2133
|
+
"read_artifacts",
|
|
2134
|
+
`Read up to ${WORKSPACE_READ_MAX_FILES} known artifact files or inclusive line ranges in one call. Paths must come from \`list_artifacts\` and stay relative to the artifact root. Pass simple \`paths\` for first chunks, or \`files\` entries with the same \`startLine\`/\`endLine\` shape as \`read_files\`; pass exactly one field. Exact workspace-file mistakes are safely rerouted only when \`read_file\` is authorized. Results stay in request order and preserve item-level errors.`,
|
|
2135
|
+
{
|
|
2136
|
+
files: z4.array(
|
|
2137
|
+
z4.object({
|
|
2138
|
+
path: z4.string().min(1).max(4096).describe("Artifact-root-relative path."),
|
|
2139
|
+
startLine: z4.number().int().min(1).max(1e7).optional().describe("1-based first line to return (inclusive). Defaults to 1."),
|
|
2140
|
+
endLine: z4.number().int().min(1).max(1e7).optional().describe(
|
|
2141
|
+
`1-based last line to return (inclusive); at most ${WORKSPACE_READ_MAX_RANGE_LINES} lines.`
|
|
2142
|
+
)
|
|
2143
|
+
})
|
|
2144
|
+
).min(1).max(WORKSPACE_READ_MAX_FILES).optional().describe("Artifact files/ranges to read, in request order."),
|
|
2145
|
+
paths: z4.array(z4.string().min(1).max(4096)).min(1).max(WORKSPACE_READ_MAX_FILES).optional().describe("Simple artifact-root-relative paths. Use `files` for ranges.")
|
|
2146
|
+
},
|
|
2147
|
+
async ({ files, paths }) => {
|
|
2148
|
+
if (files === void 0 === (paths === void 0)) {
|
|
2149
|
+
return errorResult("read_artifacts failed: pass exactly one of `paths` or `files`");
|
|
2150
|
+
}
|
|
2151
|
+
const requests = files ?? paths?.map((path) => ({ path })) ?? [];
|
|
2152
|
+
for (const request of requests) {
|
|
2153
|
+
const rangeError = workspaceReadRangeError(request);
|
|
2154
|
+
if (rangeError) return errorResult(`read_artifacts failed: ${request.path}: ${rangeError}`);
|
|
2155
|
+
}
|
|
2156
|
+
const results = await Promise.all(
|
|
2157
|
+
requests.map(async (request) => {
|
|
2158
|
+
const clean = normalizeArtifactPath2(request.path);
|
|
2159
|
+
try {
|
|
2160
|
+
const artifact = await api2.readProjectArtifactSlice(
|
|
2161
|
+
projectId2,
|
|
2162
|
+
clean,
|
|
2163
|
+
artifactSliceOpts(request)
|
|
2164
|
+
);
|
|
2165
|
+
if (artifact.kind === "found") {
|
|
2166
|
+
const start = artifactSliceStart(
|
|
2167
|
+
request,
|
|
2168
|
+
artifact.totalLines,
|
|
2169
|
+
artifact.linesReturned
|
|
2170
|
+
);
|
|
2171
|
+
const end = start + Math.max(0, artifact.linesReturned - 1);
|
|
2172
|
+
return {
|
|
2173
|
+
status: "ok",
|
|
2174
|
+
path: request.path,
|
|
2175
|
+
content: artifact.content,
|
|
2176
|
+
startLine: start,
|
|
2177
|
+
endLine: end,
|
|
2178
|
+
completeFile: artifact.linesReturned === artifact.totalLines,
|
|
2179
|
+
totalLines: artifact.totalLines,
|
|
2180
|
+
hasMore: artifact.hasMore,
|
|
2181
|
+
...artifact.hasMore ? { nextStartLine: end + 1 } : {},
|
|
2182
|
+
resolvedSurface: "artifact",
|
|
2183
|
+
resolvedPath: artifact.path,
|
|
2184
|
+
rerouted: false,
|
|
2185
|
+
fuzzy: artifact.fuzzy
|
|
2186
|
+
};
|
|
2187
|
+
}
|
|
2188
|
+
if (artifact.kind === "ambiguous") {
|
|
2189
|
+
return {
|
|
2190
|
+
status: "error",
|
|
2191
|
+
path: request.path,
|
|
2192
|
+
code: "ambiguous",
|
|
2193
|
+
error: `matches multiple artifacts: ${artifact.candidates.join(", ")}`,
|
|
2194
|
+
resolvedSurface: "artifact",
|
|
2195
|
+
rerouted: false
|
|
2196
|
+
};
|
|
2197
|
+
}
|
|
2198
|
+
const workspace = await workspaceCollisionForArtifactPath2(clean);
|
|
2199
|
+
if (!workspace || workspace.kind !== "file") {
|
|
2200
|
+
return {
|
|
2201
|
+
status: "error",
|
|
2202
|
+
path: request.path,
|
|
2203
|
+
code: "path-not-found",
|
|
2204
|
+
error: "artifact not found",
|
|
2205
|
+
resolvedSurface: "artifact",
|
|
2206
|
+
rerouted: false
|
|
2207
|
+
};
|
|
2208
|
+
}
|
|
2209
|
+
if (!toolIsAuthorized("read_file")) {
|
|
2210
|
+
return {
|
|
2211
|
+
status: "error",
|
|
2212
|
+
path: request.path,
|
|
2213
|
+
code: "workspace-read-unauthorized",
|
|
2214
|
+
error: `a workspace file exists at "${workspace.path}", but read_file is not authorized for this session`,
|
|
2215
|
+
requestedPath: request.path,
|
|
2216
|
+
resolvedPath: workspace.path,
|
|
2217
|
+
resolvedSurface: "workspace",
|
|
2218
|
+
rerouted: false
|
|
2219
|
+
};
|
|
2220
|
+
}
|
|
2221
|
+
const workspaceResult = (await readWorkspaceFiles2([
|
|
2222
|
+
{
|
|
2223
|
+
path: workspace.path,
|
|
2224
|
+
...request.startLine !== void 0 ? { startLine: request.startLine } : {},
|
|
2225
|
+
...request.endLine !== void 0 ? { endLine: request.endLine } : {}
|
|
2226
|
+
}
|
|
2227
|
+
])).results[0];
|
|
2228
|
+
if (!workspaceResult || workspaceResult.status === "error") {
|
|
2229
|
+
return {
|
|
2230
|
+
status: "error",
|
|
2231
|
+
path: request.path,
|
|
2232
|
+
code: workspaceResult?.status === "error" ? workspaceResult.code : "read-failed",
|
|
2233
|
+
error: workspaceResult?.status === "error" ? workspaceResult.error : "workspace fallback returned no result",
|
|
2234
|
+
resolvedSurface: "artifact",
|
|
2235
|
+
rerouted: false
|
|
2236
|
+
};
|
|
2237
|
+
}
|
|
2238
|
+
return {
|
|
2239
|
+
status: "ok",
|
|
2240
|
+
path: request.path,
|
|
2241
|
+
content: workspaceResult.content,
|
|
2242
|
+
startLine: workspaceResult.startLine,
|
|
2243
|
+
endLine: workspaceResult.endLine,
|
|
2244
|
+
completeFile: workspaceResult.completeFile,
|
|
2245
|
+
totalLines: workspaceResult.totalLines,
|
|
2246
|
+
hasMore: workspaceResult.hasMore,
|
|
2247
|
+
nextStartLine: workspaceResult.nextStartLine,
|
|
2248
|
+
resolvedSurface: "workspace",
|
|
2249
|
+
resolvedPath: workspace.path,
|
|
2250
|
+
rerouted: true,
|
|
2251
|
+
fuzzy: false
|
|
2252
|
+
};
|
|
2253
|
+
} catch (error) {
|
|
2254
|
+
return {
|
|
2255
|
+
status: "error",
|
|
2256
|
+
path: request.path,
|
|
2257
|
+
code: "read-failed",
|
|
2258
|
+
error: unwrapApiError2(error),
|
|
2259
|
+
resolvedSurface: "artifact",
|
|
2260
|
+
rerouted: false
|
|
2261
|
+
};
|
|
2262
|
+
}
|
|
2263
|
+
})
|
|
2264
|
+
);
|
|
2265
|
+
const index = results.map((result, index2) => {
|
|
2266
|
+
if (result.status === "error") {
|
|
2267
|
+
return `${index2 + 1} ERROR ${result.path} [${result.code}] ${result.error}`;
|
|
2268
|
+
}
|
|
2269
|
+
const route = result.rerouted ? ` rerouted=workspace:${result.resolvedPath}` : "";
|
|
2270
|
+
const next = result.nextStartLine ? ` nextStartLine=${result.nextStartLine}` : "";
|
|
2271
|
+
return `${index2 + 1} OK ${result.path} lines=${result.startLine}-${result.endLine}${result.totalLines !== void 0 ? ` totalLines=${result.totalLines}` : ""}${result.completeFile ? " complete" : ""}${next}${route}`;
|
|
2272
|
+
});
|
|
2273
|
+
const sections = results.map((result) => {
|
|
2274
|
+
if (result.status === "error") {
|
|
2275
|
+
return `--- ${result.path} [ERROR: ${result.code}] ---
|
|
2276
|
+
${result.error}`;
|
|
2277
|
+
}
|
|
2278
|
+
const notice = result.rerouted ? `${reroutedReadNotice("read_artifacts", "read_file", "workspace", result.resolvedPath)}
|
|
2279
|
+
` : "";
|
|
2280
|
+
const fuzzy = result.fuzzy ? `(matched ${result.resolvedPath} by basename)
|
|
2281
|
+
` : "";
|
|
2282
|
+
return `--- ${result.path} (lines=${result.startLine}-${result.endLine}) ---
|
|
2283
|
+
${notice}${fuzzy}${result.content}`;
|
|
2284
|
+
});
|
|
2285
|
+
const allFailed = results.length > 0 && results.every((result) => result.status === "error");
|
|
2286
|
+
return {
|
|
2287
|
+
content: [
|
|
2288
|
+
{
|
|
2289
|
+
type: "text",
|
|
2290
|
+
text: `[read_artifacts requested=${results.length} ok=${results.filter((result) => result.status === "ok").length} errors=${results.filter((result) => result.status === "error").length}]
|
|
2291
|
+
${index.join("\n")}
|
|
2292
|
+
|
|
2293
|
+
${sections.join("\n\n")}`
|
|
2294
|
+
}
|
|
2295
|
+
],
|
|
2296
|
+
structuredContent: { results },
|
|
2297
|
+
...allFailed ? { isError: true } : {}
|
|
2298
|
+
};
|
|
2299
|
+
}
|
|
2300
|
+
);
|
|
2301
|
+
}
|
|
2302
|
+
|
|
2303
|
+
// src/generate-image-normalization.ts
|
|
2304
|
+
var AGENT_IMAGE_MAX_SIDE_PX = 768;
|
|
2305
|
+
var AGENT_IMAGE_MAX_STEPS = 4;
|
|
2306
|
+
var SIZE_MULTIPLE = 64;
|
|
2307
|
+
function normalizeGenerateImageToolArgs(args) {
|
|
2308
|
+
const next = { ...args };
|
|
2309
|
+
const changes = [];
|
|
2310
|
+
const originalSize = typeof args.width === "number" && typeof args.height === "number" ? `${args.width}x${args.height}` : void 0;
|
|
2311
|
+
if (typeof args.width === "number" && typeof args.height === "number") {
|
|
2312
|
+
const maxSide = Math.max(args.width, args.height);
|
|
2313
|
+
if (maxSide > AGENT_IMAGE_MAX_SIDE_PX) {
|
|
2314
|
+
const scale = AGENT_IMAGE_MAX_SIDE_PX / maxSide;
|
|
2315
|
+
next.width = quantizeImageSize(args.width * scale);
|
|
2316
|
+
next.height = quantizeImageSize(args.height * scale);
|
|
2317
|
+
}
|
|
2318
|
+
} else if (typeof args.width === "number" && args.width > AGENT_IMAGE_MAX_SIDE_PX) {
|
|
2319
|
+
next.width = AGENT_IMAGE_MAX_SIDE_PX;
|
|
2320
|
+
} else if (typeof args.height === "number" && args.height > AGENT_IMAGE_MAX_SIDE_PX) {
|
|
2321
|
+
next.height = AGENT_IMAGE_MAX_SIDE_PX;
|
|
2322
|
+
}
|
|
2323
|
+
if (originalSize && typeof next.width === "number" && typeof next.height === "number" && `${next.width}x${next.height}` !== originalSize) {
|
|
2324
|
+
changes.push(`size ${originalSize} -> ${next.width}x${next.height}`);
|
|
2325
|
+
} else if (args.width !== next.width && typeof next.width === "number") {
|
|
2326
|
+
changes.push(`width ${args.width} -> ${next.width}`);
|
|
2327
|
+
} else if (args.height !== next.height && typeof next.height === "number") {
|
|
2328
|
+
changes.push(`height ${args.height} -> ${next.height}`);
|
|
2329
|
+
}
|
|
2330
|
+
if (typeof args.steps === "number" && args.steps > AGENT_IMAGE_MAX_STEPS) {
|
|
2331
|
+
next.steps = AGENT_IMAGE_MAX_STEPS;
|
|
2332
|
+
changes.push(`steps ${args.steps} -> ${next.steps}`);
|
|
2333
|
+
}
|
|
2334
|
+
return {
|
|
2335
|
+
args: next,
|
|
2336
|
+
...changes.length > 0 ? { note: `Request normalized for agent image generation (${changes.join(", ")}).` } : {}
|
|
2337
|
+
};
|
|
2338
|
+
}
|
|
2339
|
+
function quantizeImageSize(size) {
|
|
2340
|
+
const rounded = Math.round(size / SIZE_MULTIPLE) * SIZE_MULTIPLE;
|
|
2341
|
+
return Math.max(SIZE_MULTIPLE, Math.min(AGENT_IMAGE_MAX_SIDE_PX, rounded));
|
|
2342
|
+
}
|
|
2343
|
+
|
|
2344
|
+
// src/linked-workspace.ts
|
|
2345
|
+
function isLinkedWorkspacePath(inputPath) {
|
|
2346
|
+
const normalized = inputPath.replaceAll("\\", "/").replace(/\/{2,}/g, "/");
|
|
2347
|
+
return normalized === ".." || normalized === "../" || normalized.startsWith("../");
|
|
2348
|
+
}
|
|
2349
|
+
function resolveLinkedWorkspacePath(sourceProjectId, linkedProjectIds2, inputPath) {
|
|
2350
|
+
const normalized = inputPath.replaceAll("\\", "/").replace(/\/{2,}/g, "/");
|
|
2351
|
+
if (normalized === ".." || normalized === "../") {
|
|
2352
|
+
return { kind: "links-root", projectId: sourceProjectId, path: "..", displayPath: ".." };
|
|
2353
|
+
}
|
|
2354
|
+
if (!normalized.startsWith("../")) {
|
|
2355
|
+
return {
|
|
2356
|
+
kind: "current",
|
|
2357
|
+
projectId: sourceProjectId,
|
|
2358
|
+
path: normalized,
|
|
2359
|
+
displayPath: normalized
|
|
2360
|
+
};
|
|
2361
|
+
}
|
|
2362
|
+
const remainder = normalized.slice(3);
|
|
2363
|
+
const slash = remainder.indexOf("/");
|
|
2364
|
+
const targetProjectId = slash === -1 ? remainder : remainder.slice(0, slash);
|
|
2365
|
+
const targetPath = slash === -1 ? "" : remainder.slice(slash + 1);
|
|
2366
|
+
if (!targetProjectId || !linkedProjectIds2.includes(targetProjectId)) {
|
|
2367
|
+
const available = linkedProjectIds2.length > 0 ? linkedProjectIds2.join(", ") : "none";
|
|
2368
|
+
throw new Error(
|
|
2369
|
+
`project "${targetProjectId || "(missing)"}" is not linked from ${sourceProjectId}; linked projects: ${available}`
|
|
2370
|
+
);
|
|
2371
|
+
}
|
|
2372
|
+
return {
|
|
2373
|
+
kind: "linked",
|
|
2374
|
+
projectId: targetProjectId,
|
|
2375
|
+
path: targetPath,
|
|
2376
|
+
displayPath: linkedDisplayPath(targetProjectId, targetPath),
|
|
2377
|
+
linkedFromProjectId: sourceProjectId
|
|
2378
|
+
};
|
|
2379
|
+
}
|
|
2380
|
+
function linkedDisplayPath(projectId2, path) {
|
|
2381
|
+
return path ? `../${projectId2}/${path}` : `../${projectId2}`;
|
|
2382
|
+
}
|
|
2383
|
+
function linkedProjectEntries(projectIds) {
|
|
2384
|
+
return projectIds.map((id) => ({ name: id, path: `../${id}`, isDirectory: true }));
|
|
2385
|
+
}
|
|
2386
|
+
function prefixLinkedEntry(projectId2, entry) {
|
|
2387
|
+
return {
|
|
2388
|
+
...entry,
|
|
2389
|
+
path: linkedDisplayPath(projectId2, entry.path)
|
|
2390
|
+
};
|
|
2391
|
+
}
|
|
2392
|
+
|
|
2393
|
+
// src/normalize.ts
|
|
2394
|
+
function normalizeMarkdown(input) {
|
|
2395
|
+
if (!input) return input;
|
|
2396
|
+
const segments = splitByFences(input);
|
|
2397
|
+
const out = [];
|
|
2398
|
+
for (const seg of segments) {
|
|
2399
|
+
if (seg.fenced) {
|
|
2400
|
+
out.push(seg.text);
|
|
2401
|
+
} else {
|
|
2402
|
+
out.push(collapseParagraphs(seg.text));
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
return out.join("");
|
|
2406
|
+
}
|
|
2407
|
+
function splitByFences(input) {
|
|
2408
|
+
const fenceRe = /^(`{3,}|~{3,})[^\n]*\n[\s\S]*?^\1[^\n]*$/gm;
|
|
2409
|
+
const segments = [];
|
|
2410
|
+
let last = 0;
|
|
2411
|
+
for (const m of input.matchAll(fenceRe)) {
|
|
2412
|
+
const idx = m.index ?? 0;
|
|
2413
|
+
if (idx > last) {
|
|
2414
|
+
segments.push({ fenced: false, text: input.slice(last, idx) });
|
|
2415
|
+
}
|
|
2416
|
+
segments.push({ fenced: true, text: m[0] });
|
|
2417
|
+
last = idx + m[0].length;
|
|
2418
|
+
}
|
|
2419
|
+
if (last < input.length) {
|
|
2420
|
+
segments.push({ fenced: false, text: input.slice(last) });
|
|
2421
|
+
}
|
|
2422
|
+
return segments;
|
|
2423
|
+
}
|
|
2424
|
+
function collapseParagraphs(text) {
|
|
2425
|
+
const lines = text.split("\n");
|
|
2426
|
+
const result = [];
|
|
2427
|
+
let buf = [];
|
|
2428
|
+
const flush = () => {
|
|
2429
|
+
if (buf.length) {
|
|
2430
|
+
result.push(buf.join(" "));
|
|
2431
|
+
buf = [];
|
|
2432
|
+
}
|
|
2433
|
+
};
|
|
2434
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2435
|
+
const line = lines[i] ?? "";
|
|
2436
|
+
const trimmed = line.trim();
|
|
2437
|
+
if (trimmed === "") {
|
|
2438
|
+
flush();
|
|
2439
|
+
result.push("");
|
|
2440
|
+
continue;
|
|
2441
|
+
}
|
|
2442
|
+
if (line.endsWith(" ")) {
|
|
2443
|
+
if (buf.length) buf.push(trimmed);
|
|
2444
|
+
else buf.push(line);
|
|
2445
|
+
flush();
|
|
2446
|
+
continue;
|
|
2447
|
+
}
|
|
2448
|
+
if (isStandaloneBlock(trimmed)) {
|
|
2449
|
+
flush();
|
|
2450
|
+
result.push(line.replace(/\s+$/, ""));
|
|
2451
|
+
continue;
|
|
2452
|
+
}
|
|
2453
|
+
if (isContinuableBlock(trimmed)) {
|
|
2454
|
+
flush();
|
|
2455
|
+
buf.push(line.replace(/\s+$/, ""));
|
|
2456
|
+
continue;
|
|
2457
|
+
}
|
|
2458
|
+
buf.push(trimmed);
|
|
2459
|
+
}
|
|
2460
|
+
flush();
|
|
2461
|
+
return result.join("\n");
|
|
2462
|
+
}
|
|
2463
|
+
function isStandaloneBlock(trimmed) {
|
|
2464
|
+
if (/^#{1,6}\s/.test(trimmed)) return true;
|
|
2465
|
+
if (/^-{3,}$|^={3,}$|^\*{3,}$|^_{3,}$/.test(trimmed)) return true;
|
|
2466
|
+
return false;
|
|
2467
|
+
}
|
|
2468
|
+
function isContinuableBlock(trimmed) {
|
|
2469
|
+
if (/^(?:[-*+])\s/.test(trimmed)) return true;
|
|
2470
|
+
if (/^\d+[.)]\s/.test(trimmed)) return true;
|
|
2471
|
+
if (/^>/.test(trimmed)) return true;
|
|
2472
|
+
if (/^\|/.test(trimmed)) return true;
|
|
2473
|
+
return false;
|
|
2474
|
+
}
|
|
2475
|
+
|
|
2476
|
+
// src/partial-edits.ts
|
|
2477
|
+
var CAP = 12;
|
|
2478
|
+
var GATED_TOOLS = /* @__PURE__ */ new Set(["advance_task_step", "verify_outcome"]);
|
|
2479
|
+
var PartialEditRegistry = class {
|
|
2480
|
+
drafts = /* @__PURE__ */ new Map();
|
|
2481
|
+
/**
|
|
2482
|
+
* Record a provisional edit. `priorContent` is only kept the first
|
|
2483
|
+
* time — it is the last state the file was in before the sequence
|
|
2484
|
+
* started, not the previous provisional step.
|
|
2485
|
+
*/
|
|
2486
|
+
record(path, priorContent) {
|
|
2487
|
+
const existing = this.drafts.get(path);
|
|
2488
|
+
if (existing) {
|
|
2489
|
+
existing.edits += 1;
|
|
2490
|
+
return existing;
|
|
2491
|
+
}
|
|
2492
|
+
const created = { path, edits: 1, snapshot: priorContent };
|
|
2493
|
+
this.drafts.set(path, created);
|
|
2494
|
+
return created;
|
|
2495
|
+
}
|
|
2496
|
+
get(path) {
|
|
2497
|
+
return this.drafts.get(path);
|
|
2498
|
+
}
|
|
2499
|
+
isOpen(path) {
|
|
2500
|
+
return this.drafts.has(path);
|
|
2501
|
+
}
|
|
2502
|
+
/** Called when a path validates cleanly again, by any write path. */
|
|
2503
|
+
close(path) {
|
|
2504
|
+
const draft = this.drafts.get(path);
|
|
2505
|
+
if (draft) this.drafts.delete(path);
|
|
2506
|
+
return draft;
|
|
2507
|
+
}
|
|
2508
|
+
openPaths() {
|
|
2509
|
+
return [...this.drafts.keys()].sort();
|
|
2510
|
+
}
|
|
2511
|
+
/**
|
|
2512
|
+
* Why `toolName` may not run, or null. Mirrors the unresolved-tool
|
|
2513
|
+
* failure ledger: narrow set of gated tools, and `set_task_status`
|
|
2514
|
+
* stays open so a stuck gezel keeps an honest exit.
|
|
2515
|
+
*/
|
|
2516
|
+
blockReason(toolName) {
|
|
2517
|
+
if (!GATED_TOOLS.has(toolName)) return null;
|
|
2518
|
+
const open = this.openPaths();
|
|
2519
|
+
if (open.length === 0) return null;
|
|
2520
|
+
const list = open.map((p) => `\`${p}\``).join(", ");
|
|
2521
|
+
return [
|
|
2522
|
+
`${toolName} is blocked: ${open.length === 1 ? "a file is" : "files are"} still in a provisional edit sequence (${list}).`,
|
|
2523
|
+
"Those edits were accepted without the syntax gate because you passed `partial: true`, so the file is not known to parse.",
|
|
2524
|
+
"Finish the sequence with a final edit that omits `partial`, or re-emit the whole file with `write_file`.",
|
|
2525
|
+
`Then re-run \`validate\` and call ${toolName} again.`
|
|
2526
|
+
].join(" ");
|
|
2527
|
+
}
|
|
2528
|
+
/** Model-facing note appended to a provisional edit's result. */
|
|
2529
|
+
noticeFor(draft) {
|
|
2530
|
+
const left = CAP - draft.edits;
|
|
2531
|
+
const parts = [
|
|
2532
|
+
`[Provisional edit ${draft.edits} of at most ${CAP}] \`${draft.path}\` is a draft and was NOT syntax-checked.`,
|
|
2533
|
+
"Nothing that declares work finished will run until it parses again.",
|
|
2534
|
+
`Close the sequence with a final edit that omits \`partial\`, then call \`validate({ path: "${draft.path}" })\`.`
|
|
2535
|
+
];
|
|
2536
|
+
if (left <= 3) {
|
|
2537
|
+
parts.push(`Only ${left} provisional edit(s) remain before the sequence is reverted.`);
|
|
2538
|
+
}
|
|
2539
|
+
return `
|
|
2540
|
+
|
|
2541
|
+
${parts.join(" ")}`;
|
|
2542
|
+
}
|
|
2543
|
+
};
|
|
2544
|
+
|
|
2545
|
+
// src/platform-tool-availability.ts
|
|
2546
|
+
import { spawnSync } from "child_process";
|
|
2547
|
+
var DENY_NET_TOOLS = ["run_nodejs_script", "derive_file"];
|
|
2548
|
+
var SCRIPT_NETWORK_ALLOWED_ENV = "GEZEL_SCRIPT_NETWORK_ALLOWED";
|
|
2549
|
+
var linuxSystemdProbe;
|
|
2550
|
+
function canUseLinuxSystemdDenyNet() {
|
|
2551
|
+
if (process.platform !== "linux") return false;
|
|
2552
|
+
if (linuxSystemdProbe !== void 0) return linuxSystemdProbe;
|
|
2553
|
+
const probe = "const net=require('node:net');const s=net.connect({host:'127.0.0.1',port:9});s.once('connect',()=>process.exit(9));s.once('error',e=>process.exit(['EAFNOSUPPORT','EPERM','EACCES'].includes(e.code)?0:2));setTimeout(()=>process.exit(3),1000);";
|
|
2554
|
+
const result = spawnSync(
|
|
2555
|
+
"systemd-run",
|
|
2556
|
+
[
|
|
2557
|
+
"--user",
|
|
2558
|
+
"--quiet",
|
|
2559
|
+
"--pipe",
|
|
2560
|
+
"--wait",
|
|
2561
|
+
"--collect",
|
|
2562
|
+
"-p",
|
|
2563
|
+
"RestrictAddressFamilies=AF_UNIX",
|
|
2564
|
+
"-p",
|
|
2565
|
+
"RuntimeMaxSec=3",
|
|
2566
|
+
"--",
|
|
2567
|
+
process.execPath,
|
|
2568
|
+
"-e",
|
|
2569
|
+
probe
|
|
2570
|
+
],
|
|
2571
|
+
{ stdio: "ignore", timeout: 3e3 }
|
|
2572
|
+
);
|
|
2573
|
+
linuxSystemdProbe = result.status === 0;
|
|
2574
|
+
return linuxSystemdProbe;
|
|
2575
|
+
}
|
|
2576
|
+
function unavailableToolsForPlatform(platform, options = {}) {
|
|
2577
|
+
if (platform === "darwin") return [];
|
|
2578
|
+
if (platform === "linux" && (options.linuxSystemdAvailable ?? canUseLinuxSystemdDenyNet())) {
|
|
2579
|
+
return [];
|
|
2580
|
+
}
|
|
2581
|
+
if (options.networkAllowed) return [];
|
|
2582
|
+
return DENY_NET_TOOLS;
|
|
2583
|
+
}
|
|
2584
|
+
|
|
2585
|
+
// src/question-prompt.ts
|
|
2586
|
+
function composeQuestionPrompt(parts) {
|
|
2587
|
+
const unique = [];
|
|
2588
|
+
for (const value of [parts.question, parts.prompt, parts.description]) {
|
|
2589
|
+
const trimmed = value?.trim();
|
|
2590
|
+
if (trimmed && !unique.includes(trimmed)) unique.push(trimmed);
|
|
2591
|
+
}
|
|
2592
|
+
return unique.join("\n\n");
|
|
2593
|
+
}
|
|
2594
|
+
function resolveQuestionTaskRef(explicitTaskRef, sessionTaskRef2) {
|
|
2595
|
+
return explicitTaskRef ?? (sessionTaskRef2.trim() || void 0);
|
|
2596
|
+
}
|
|
2597
|
+
|
|
2598
|
+
// src/repo-intake-policy.ts
|
|
2599
|
+
var GITHUB_REPO_URL_RE = /https?:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]*[A-Za-z0-9_-])(?:\.git)?(?:\/[^\s)"'`<>]*)?/i;
|
|
2600
|
+
function extractGitHubRepoUrl(text) {
|
|
2601
|
+
const match = text.match(GITHUB_REPO_URL_RE);
|
|
2602
|
+
if (!match) return void 0;
|
|
2603
|
+
const owner = match[1];
|
|
2604
|
+
const repo = match[2]?.replace(/\.git$/i, "");
|
|
2605
|
+
if (!owner || !repo) return void 0;
|
|
2606
|
+
return `https://github.com/${owner}/${repo}`;
|
|
2607
|
+
}
|
|
2608
|
+
function knownRepoShortcut(text) {
|
|
2609
|
+
if (/\bsquisq\b/i.test(text)) {
|
|
2610
|
+
return { url: "https://github.com/bendyline/squisq", projectName: "Squisq Code Review" };
|
|
2611
|
+
}
|
|
2612
|
+
return null;
|
|
2613
|
+
}
|
|
2614
|
+
function titleCaseRepoName(repo) {
|
|
2615
|
+
return repo.split(/[-_\s]+/).filter(Boolean).map((part) => `${part.slice(0, 1).toUpperCase()}${part.slice(1).toLowerCase()}`).join(" ");
|
|
2616
|
+
}
|
|
2617
|
+
function projectNameFromUrl(url) {
|
|
2618
|
+
const repo = url.split("/").pop() || "Repository";
|
|
2619
|
+
return `${titleCaseRepoName(repo)} Code Review`;
|
|
2620
|
+
}
|
|
2621
|
+
function looksLikeRepoSourceWork(text, hasUrl) {
|
|
2622
|
+
if (/\b(review|audit|analy[sz]e|analysis|inspect|architecture|codebase|source code|walk the source|read (?:the )?source|fix|debug|change|work with)\b/i.test(
|
|
2623
|
+
text
|
|
2624
|
+
)) {
|
|
2625
|
+
return true;
|
|
2626
|
+
}
|
|
2627
|
+
return hasUrl && /\b(repo|repository|clone|fetch_repo)\b/i.test(text);
|
|
2628
|
+
}
|
|
2629
|
+
function repoIntakeRedirect(input) {
|
|
2630
|
+
const url = extractGitHubRepoUrl(input.text);
|
|
2631
|
+
const shortcut = url ? null : knownRepoShortcut(input.text);
|
|
2632
|
+
const targetUrl = url ?? shortcut?.url;
|
|
2633
|
+
if (!targetUrl || !looksLikeRepoSourceWork(input.text, Boolean(url))) return null;
|
|
2634
|
+
const projectName = input.projectName?.trim() || shortcut?.projectName || projectNameFromUrl(targetUrl);
|
|
2635
|
+
const fetchCall = `fetch_repo({ url: "${targetUrl}", projectName: "${projectName}" })`;
|
|
2636
|
+
const prefix = input.mode === "macro" ? `${input.tool} is the wrong macro for remote repository review/analysis because it creates an empty bootstrap project with no source code.` : `${input.tool} cannot hand off remote repository work from this project until the source repository has been fetched.`;
|
|
2637
|
+
return {
|
|
2638
|
+
url: targetUrl,
|
|
2639
|
+
projectName,
|
|
2640
|
+
message: `${prefix} Call \`${fetchCall}\` first; that creates the project and clones the repository into the workspace root. After it returns, pass the returned projectId to any reviewer or specialist. Do not ask the user to paste source code.`
|
|
1759
2641
|
};
|
|
1760
2642
|
}
|
|
1761
2643
|
|
|
1762
2644
|
// src/script-tools.ts
|
|
2645
|
+
import {
|
|
2646
|
+
ProjectTypeToolSchema
|
|
2647
|
+
} from "@bendyline/gezel";
|
|
2648
|
+
import { z as z5 } from "zod";
|
|
1763
2649
|
function warn(message) {
|
|
1764
2650
|
process.stderr.write(`gezel-mcp script-tools: ${message}
|
|
1765
2651
|
`);
|
|
@@ -1911,6 +2797,25 @@ function policyForDeliverable(deliverablePath, briefText) {
|
|
|
1911
2797
|
function craftbookPinFloor(topSemantic) {
|
|
1912
2798
|
return typeof topSemantic === "number" ? 0.3 : 0.07;
|
|
1913
2799
|
}
|
|
2800
|
+
function producerToolsFor(policy) {
|
|
2801
|
+
if (policy.isRasterImage) return { group: "images", tools: ["generate_image"] };
|
|
2802
|
+
if (policy.isData)
|
|
2803
|
+
return { group: "code-execution", tools: ["derive_file", "run_nodejs_script"] };
|
|
2804
|
+
return void 0;
|
|
2805
|
+
}
|
|
2806
|
+
function retargetEntryToolPolicy(policy, toolPolicy) {
|
|
2807
|
+
const producer = producerToolsFor(policy);
|
|
2808
|
+
if (!producer || !toolPolicy) return toolPolicy;
|
|
2809
|
+
const next = { ...toolPolicy };
|
|
2810
|
+
const groups = next.disallowBuiltinToolsets?.filter((g) => g !== producer.group);
|
|
2811
|
+
if (groups?.length) next.disallowBuiltinToolsets = groups;
|
|
2812
|
+
else delete next.disallowBuiltinToolsets;
|
|
2813
|
+
const deniedTools = next.disallowTools?.filter((t) => !producer.tools.includes(t));
|
|
2814
|
+
if (deniedTools?.length) next.disallowTools = deniedTools;
|
|
2815
|
+
else delete next.disallowTools;
|
|
2816
|
+
if (next.allowTools) next.allowTools = [.../* @__PURE__ */ new Set([...next.allowTools, ...producer.tools])];
|
|
2817
|
+
return next;
|
|
2818
|
+
}
|
|
1914
2819
|
function retargetGateLayers(policy, deliverablePath, gate, extraChecks = []) {
|
|
1915
2820
|
if (policy.isHtml) {
|
|
1916
2821
|
const checks2 = [
|
|
@@ -2300,7 +3205,8 @@ function taskStepMutationRejection(scope) {
|
|
|
2300
3205
|
if (!taskRef || !sessionStepId2) return null;
|
|
2301
3206
|
if (!transitionCompleted && activeStepId === sessionStepId2) return null;
|
|
2302
3207
|
const active = activeStepId ? ` The active step is now "${activeStepId}".` : " This session already completed its step.";
|
|
2303
|
-
|
|
3208
|
+
const yieldTo = activeStepId && scope.activeStepOwnedBySession ? `That step is yours as well: end this turn now, and the runtime re-engages you with the "${activeStepId}" procedure in front of you.` : "Stop this turn and yield to the active step's gezel.";
|
|
3209
|
+
return `Step "${sessionStepId2}" on ${taskRef} no longer owns project writes.${active} ${yieldTo} Do not rewrite, append to, move, or delete the completed step's deliverable.`;
|
|
2304
3210
|
}
|
|
2305
3211
|
|
|
2306
3212
|
// src/validate.ts
|
|
@@ -3268,14 +4174,23 @@ var linkedFetchImpl = (input, init) => {
|
|
|
3268
4174
|
};
|
|
3269
4175
|
var linkedApi = new GezelClient({ baseUrl, token, fetch: linkedFetchImpl });
|
|
3270
4176
|
var sessionStepCompleted = false;
|
|
4177
|
+
var sessionStepCompletion = "unknown";
|
|
3271
4178
|
async function staleStepMutationResult() {
|
|
3272
4179
|
if (!sessionTaskRef || !sessionStepId) return null;
|
|
4180
|
+
sessionStepCompletion = "unknown";
|
|
3273
4181
|
let activeStepId;
|
|
4182
|
+
let activeStepOwnedBySession = false;
|
|
3274
4183
|
if (!sessionStepCompleted) {
|
|
3275
4184
|
try {
|
|
3276
4185
|
const parsed = await parseRef(sessionTaskRef);
|
|
3277
4186
|
const task = await api.getTask(parsed.projectId, parsed.num);
|
|
3278
4187
|
activeStepId = task.activeStepId;
|
|
4188
|
+
const activeStep = task.craftbook.steps.find((s) => s.id === activeStepId);
|
|
4189
|
+
if (activeStep && activeStepId === sessionStepId) {
|
|
4190
|
+
sessionStepCompletion = activeStep.advanceWhen ? "automatic" : "manual";
|
|
4191
|
+
}
|
|
4192
|
+
const owner = activeStep ? stepOwnerGezelId(task, activeStep) : void 0;
|
|
4193
|
+
activeStepOwnedBySession = !!gezelId && owner === gezelId;
|
|
3279
4194
|
} catch {
|
|
3280
4195
|
return null;
|
|
3281
4196
|
}
|
|
@@ -3284,10 +4199,33 @@ async function staleStepMutationResult() {
|
|
|
3284
4199
|
taskRef: sessionTaskRef,
|
|
3285
4200
|
sessionStepId,
|
|
3286
4201
|
activeStepId,
|
|
3287
|
-
transitionCompleted: sessionStepCompleted
|
|
4202
|
+
transitionCompleted: sessionStepCompleted,
|
|
4203
|
+
activeStepOwnedBySession
|
|
3288
4204
|
});
|
|
3289
4205
|
return rejection ? errorResult(rejection, { code: "stale_task_step", retryable: false }) : null;
|
|
3290
4206
|
}
|
|
4207
|
+
var liveTaskCache = null;
|
|
4208
|
+
async function taskScopedWriteRefusal(path, surface) {
|
|
4209
|
+
if (sessionTaskRef) return null;
|
|
4210
|
+
let tasks;
|
|
4211
|
+
if (liveTaskCache && liveTaskCache.expiresAt > Date.now()) {
|
|
4212
|
+
tasks = liveTaskCache.tasks;
|
|
4213
|
+
} else {
|
|
4214
|
+
try {
|
|
4215
|
+
const res = await api.listProjectTasks(projectId);
|
|
4216
|
+
tasks = res.tasks;
|
|
4217
|
+
} catch {
|
|
4218
|
+
return null;
|
|
4219
|
+
}
|
|
4220
|
+
liveTaskCache = { tasks, expiresAt: Date.now() + 2e3 };
|
|
4221
|
+
}
|
|
4222
|
+
const denial = deniedTaskScopedWrite({ path, surface, owned: taskOwnedPrefixes(tasks) });
|
|
4223
|
+
if (!denial) return null;
|
|
4224
|
+
return errorResult(taskScopedWriteDeniedMessage(denial, path), {
|
|
4225
|
+
code: "task_scoped_write_denied",
|
|
4226
|
+
retryable: false
|
|
4227
|
+
});
|
|
4228
|
+
}
|
|
3291
4229
|
var linkedIdsCache = null;
|
|
3292
4230
|
async function linkedProjectIds() {
|
|
3293
4231
|
if (linkedIdsCache && linkedIdsCache.expiresAt > Date.now()) return linkedIdsCache.ids;
|
|
@@ -3447,7 +4385,9 @@ var excludedToolNames = new Set(
|
|
|
3447
4385
|
// `GEZEL_MCP_SCHEMA_LINT` registers the whole corpus regardless of what
|
|
3448
4386
|
// this host can actually sandbox, so schema lints and tool-response
|
|
3449
4387
|
// tests see the same tools everywhere.
|
|
3450
|
-
...process.env.GEZEL_MCP_SCHEMA_LINT === "1" ? [] : unavailableToolsForPlatform(process.platform
|
|
4388
|
+
...process.env.GEZEL_MCP_SCHEMA_LINT === "1" ? [] : unavailableToolsForPlatform(process.platform, {
|
|
4389
|
+
networkAllowed: process.env[SCRIPT_NETWORK_ALLOWED_ENV] === "1"
|
|
4390
|
+
}),
|
|
3451
4391
|
...distributionWithheldTools()
|
|
3452
4392
|
].map(canonicalToolName)
|
|
3453
4393
|
);
|
|
@@ -3469,6 +4409,10 @@ var allowEnv = process.env.GEZEL_MCP_ALLOW;
|
|
|
3469
4409
|
var allowedToolNames = allowEnv === void 0 ? null : new Set(
|
|
3470
4410
|
allowEnv.split(",").map((s) => s.trim()).filter(Boolean).map(canonicalToolName)
|
|
3471
4411
|
);
|
|
4412
|
+
var authorizedEnv = process.env.GEZEL_MCP_AUTHORIZED_TOOLS;
|
|
4413
|
+
var authorizedToolNames = authorizedEnv === void 0 ? null : new Set(
|
|
4414
|
+
authorizedEnv.split(",").map((s) => s.trim()).filter(Boolean).map(canonicalToolName)
|
|
4415
|
+
);
|
|
3472
4416
|
var legacyNamingMode = process.env.GEZEL_MCP_TOOL_NAMING === "legacy";
|
|
3473
4417
|
function registeredToolRegistry() {
|
|
3474
4418
|
return server._registeredTools;
|
|
@@ -3542,10 +4486,7 @@ function isZodRawShape(value) {
|
|
|
3542
4486
|
server.tool(
|
|
3543
4487
|
"search_memory",
|
|
3544
4488
|
"Search agent and project memories using semantic similarity. Returns the most relevant remembered facts, decisions, and context.",
|
|
3545
|
-
|
|
3546
|
-
query: z6.string().describe("What to search for in memory"),
|
|
3547
|
-
topK: z6.number().int().positive().max(50).optional().describe("Max memories to return (default 10).")
|
|
3548
|
-
},
|
|
4489
|
+
SearchMemoryInputSchema.shape,
|
|
3549
4490
|
async ({ query, topK }) => {
|
|
3550
4491
|
try {
|
|
3551
4492
|
const res = await fetchImpl(`${baseUrl}/api/memory/search`, {
|
|
@@ -3586,15 +4527,7 @@ ${formatted}` : summary }
|
|
|
3586
4527
|
server.tool(
|
|
3587
4528
|
"save_memory",
|
|
3588
4529
|
"Save an important fact, decision, preference, or context to memory so you can recall it later. Use this when you learn something worth remembering.",
|
|
3589
|
-
|
|
3590
|
-
text: z6.string().describe("The memory to save \u2014 a concise fact or observation"),
|
|
3591
|
-
scope: z6.enum(["gezel", "project"]).describe(
|
|
3592
|
-
'Where to save: "gezel" for your own personal memories, "project" for project-shared context'
|
|
3593
|
-
),
|
|
3594
|
-
kind: z6.enum(["fact", "decision", "pref", "status"]).optional().describe(
|
|
3595
|
-
'What kind of memory: "fact" (durable fact \u2014 the default), "decision" (a choice made), "pref" (a preference or working style), "status" (a temporary condition true right now)'
|
|
3596
|
-
)
|
|
3597
|
-
},
|
|
4530
|
+
SaveMemoryInputSchema.shape,
|
|
3598
4531
|
async ({ text, scope, kind }) => {
|
|
3599
4532
|
try {
|
|
3600
4533
|
const res = await fetchImpl(`${baseUrl}/api/memory/save`, {
|
|
@@ -4125,9 +5058,7 @@ if (process.env.GEZEL_TABLES_ENABLED === "1") {
|
|
|
4125
5058
|
server.tool(
|
|
4126
5059
|
"list_dir",
|
|
4127
5060
|
"List the files and subdirectories at a path in the project. The project root is the default. When this project links other projects, list `..` to discover them and use `../<project-id>/...` to browse one with this same tool.",
|
|
4128
|
-
|
|
4129
|
-
path: z6.string().optional().describe("Subdirectory path to list (default: project root).")
|
|
4130
|
-
},
|
|
5061
|
+
ListDirectoryInputSchema.shape,
|
|
4131
5062
|
async ({ path }) => {
|
|
4132
5063
|
try {
|
|
4133
5064
|
const target = await workspaceTarget(path ?? "");
|
|
@@ -4151,204 +5082,20 @@ ${listing}` : summary }
|
|
|
4151
5082
|
}
|
|
4152
5083
|
}
|
|
4153
5084
|
);
|
|
4154
|
-
|
|
4155
|
-
|
|
4156
|
-
|
|
4157
|
-
|
|
4158
|
-
|
|
4159
|
-
|
|
4160
|
-
|
|
4161
|
-
|
|
4162
|
-
|
|
4163
|
-
|
|
4164
|
-
|
|
4165
|
-
|
|
4166
|
-
|
|
4167
|
-
|
|
4168
|
-
if (rangeError) throw new Error(rangeError);
|
|
4169
|
-
if (raw && (startLine !== void 0 || endLine !== void 0)) {
|
|
4170
|
-
throw new Error(
|
|
4171
|
-
"`raw: true` cannot be combined with a line range; omit `raw` for a numbered range"
|
|
4172
|
-
);
|
|
4173
|
-
}
|
|
4174
|
-
if (startLine === void 0 && endLine === void 0) {
|
|
4175
|
-
const res = await readWorkspaceFile(path);
|
|
4176
|
-
return {
|
|
4177
|
-
content: [
|
|
4178
|
-
{ type: "text", text: raw ? res.content : withLineNumbers(res.content) }
|
|
4179
|
-
]
|
|
4180
|
-
};
|
|
4181
|
-
}
|
|
4182
|
-
const response = await readWorkspaceFiles([
|
|
4183
|
-
{
|
|
4184
|
-
path,
|
|
4185
|
-
...startLine !== void 0 ? { startLine } : {},
|
|
4186
|
-
...endLine !== void 0 ? { endLine } : {}
|
|
4187
|
-
}
|
|
4188
|
-
]);
|
|
4189
|
-
const result = response.results[0];
|
|
4190
|
-
if (!result) throw new Error("ranged read returned no result");
|
|
4191
|
-
if (result.status === "error") throw new Error(`[${result.code}] ${result.error}`);
|
|
4192
|
-
return {
|
|
4193
|
-
content: [{ type: "text", text: formatWorkspaceRead(result, raw === true) }]
|
|
4194
|
-
};
|
|
4195
|
-
} catch (err) {
|
|
4196
|
-
const base = unwrapApiError(err);
|
|
4197
|
-
let text = `read_file "${path}": ${base}`;
|
|
4198
|
-
if (/not found|404|no such file/i.test(base)) {
|
|
4199
|
-
const artifactCollision = await artifactCollisionForWorkspacePath(path);
|
|
4200
|
-
if (artifactCollision) {
|
|
4201
|
-
text += `. A project artifact exists at "${artifactCollision}". The workspace and artifacts are separate drawers; call read_artifact({ path: ${JSON.stringify(artifactCollision)} }) instead of read_file. The artifact was not opened automatically.`;
|
|
4202
|
-
return { content: [{ type: "text", text }], isError: true };
|
|
4203
|
-
}
|
|
4204
|
-
try {
|
|
4205
|
-
const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
|
|
4206
|
-
const targetDir = await concreteWorkspaceTarget(dir);
|
|
4207
|
-
const listing = await workspaceClient(targetDir).listProjectWorkspace(
|
|
4208
|
-
targetDir.projectId,
|
|
4209
|
-
targetDir.path,
|
|
4210
|
-
false
|
|
4211
|
-
);
|
|
4212
|
-
const names = listing.files.filter((f) => !f.isDirectory).map((f) => f.path.split("/").pop() ?? f.path);
|
|
4213
|
-
const target = path.split("/").pop() ?? path;
|
|
4214
|
-
const near = closestFileNames(target, names);
|
|
4215
|
-
const where = dir === "" ? "the project root" : `${dir}/`;
|
|
4216
|
-
if (near.length > 0) {
|
|
4217
|
-
text += `. Nearest existing in ${where}: ${near.join(", ")}`;
|
|
4218
|
-
} else if (names.length > 0) {
|
|
4219
|
-
text += `. ${where} contains: ${names.slice(0, 10).join(", ")}${names.length > 10 ? ", \u2026" : ""}`;
|
|
4220
|
-
}
|
|
4221
|
-
} catch {
|
|
4222
|
-
}
|
|
4223
|
-
}
|
|
4224
|
-
return { content: [{ type: "text", text }], isError: true };
|
|
4225
|
-
}
|
|
4226
|
-
}
|
|
4227
|
-
);
|
|
4228
|
-
server.tool(
|
|
4229
|
-
"read_files",
|
|
4230
|
-
`Read up to ${WORKSPACE_READ_MAX_FILES} known workspace files or line ranges in one call. Pass simple \`paths\` for whole-file first chunks, or richer \`files\` entries with inclusive startLine/endLine ranges; pass exactly one of those fields. Use this for independent files you already identified and grep_files/find_files first when paths are unknown. Results stay in request order and report item-level errors without discarding successful reads.`,
|
|
4231
|
-
{
|
|
4232
|
-
files: z6.array(
|
|
4233
|
-
z6.object({
|
|
4234
|
-
path: z6.string().min(1).max(4096).describe("Workspace-relative file path."),
|
|
4235
|
-
startLine: z6.number().int().min(1).max(1e7).optional().describe("1-based first line to return (inclusive). Defaults to 1."),
|
|
4236
|
-
endLine: z6.number().int().min(1).max(1e7).optional().describe(
|
|
4237
|
-
`1-based last line to return (inclusive); at most ${WORKSPACE_READ_MAX_RANGE_LINES} lines.`
|
|
4238
|
-
)
|
|
4239
|
-
})
|
|
4240
|
-
).min(1).max(WORKSPACE_READ_MAX_FILES).optional().describe("Files/ranges to read, in the order their results should be returned."),
|
|
4241
|
-
paths: z6.array(z6.string().min(1).max(4096)).min(1).max(WORKSPACE_READ_MAX_FILES).optional().describe(
|
|
4242
|
-
"Simple workspace-relative paths. Use `files` instead when any path needs a range."
|
|
4243
|
-
)
|
|
4244
|
-
},
|
|
4245
|
-
async ({ files, paths }) => {
|
|
4246
|
-
try {
|
|
4247
|
-
if (files === void 0 === (paths === void 0)) {
|
|
4248
|
-
throw new Error("pass exactly one of `paths` or `files`");
|
|
4249
|
-
}
|
|
4250
|
-
const requests = files ?? paths?.map((path) => ({ path })) ?? [];
|
|
4251
|
-
for (const request of requests) {
|
|
4252
|
-
const rangeError = workspaceReadRangeError(request);
|
|
4253
|
-
if (rangeError) throw new Error(`${request.path}: ${rangeError}`);
|
|
4254
|
-
}
|
|
4255
|
-
const response = await readWorkspaceFiles(requests);
|
|
4256
|
-
const index = response.results.map((result, index2) => {
|
|
4257
|
-
if (result.status === "error") {
|
|
4258
|
-
return `${index2 + 1} ERROR ${result.path} [${result.code}] ${result.error}`;
|
|
4259
|
-
}
|
|
4260
|
-
const next = result.nextStartLine ? ` nextStartLine=${result.nextStartLine}` : "";
|
|
4261
|
-
return `${index2 + 1} OK ${result.path} ${workspaceReadRangeLabel(result)}${result.completeFile ? " complete" : ""}${next}`;
|
|
4262
|
-
});
|
|
4263
|
-
const sections = response.results.map((result) => {
|
|
4264
|
-
if (result.status === "error") {
|
|
4265
|
-
return `--- ${result.path} [ERROR: ${result.code}] ---
|
|
4266
|
-
${result.error}`;
|
|
4267
|
-
}
|
|
4268
|
-
const range = workspaceReadRangeLabel(result);
|
|
4269
|
-
const body = withLineNumbers(result.content, result.startLine) || "(no lines returned)";
|
|
4270
|
-
const hint = workspaceReadHint(result);
|
|
4271
|
-
return `--- ${result.path} (${range}) ---
|
|
4272
|
-
${body}${hint}`;
|
|
4273
|
-
});
|
|
4274
|
-
const allFailed = response.results.length > 0 && response.results.every((r) => r.status === "error");
|
|
4275
|
-
return {
|
|
4276
|
-
content: [
|
|
4277
|
-
{
|
|
4278
|
-
type: "text",
|
|
4279
|
-
text: `[read_files requested=${response.results.length} ok=${response.results.filter((r) => r.status === "ok").length} errors=${response.results.filter((r) => r.status === "error").length}]
|
|
4280
|
-
${index.join("\n")}
|
|
4281
|
-
|
|
4282
|
-
${sections.join("\n\n")}`
|
|
4283
|
-
}
|
|
4284
|
-
],
|
|
4285
|
-
// Structured-first hosts need the same file slices, pagination, and
|
|
4286
|
-
// item-level errors that the formatted text exposes.
|
|
4287
|
-
structuredContent: {
|
|
4288
|
-
results: response.results.map(
|
|
4289
|
-
(result) => result.status === "ok" ? {
|
|
4290
|
-
path: result.path,
|
|
4291
|
-
status: result.status,
|
|
4292
|
-
content: result.content,
|
|
4293
|
-
startLine: result.startLine,
|
|
4294
|
-
endLine: result.endLine,
|
|
4295
|
-
completeFile: result.completeFile,
|
|
4296
|
-
totalLines: result.totalLines,
|
|
4297
|
-
hasMore: result.hasMore,
|
|
4298
|
-
nextStartLine: result.nextStartLine
|
|
4299
|
-
} : {
|
|
4300
|
-
path: result.path,
|
|
4301
|
-
status: result.status,
|
|
4302
|
-
code: result.code,
|
|
4303
|
-
error: result.error
|
|
4304
|
-
}
|
|
4305
|
-
)
|
|
4306
|
-
},
|
|
4307
|
-
...allFailed ? { isError: true } : {}
|
|
4308
|
-
};
|
|
4309
|
-
} catch (err) {
|
|
4310
|
-
return {
|
|
4311
|
-
content: [{ type: "text", text: `read_files failed: ${unwrapApiError(err)}` }],
|
|
4312
|
-
isError: true
|
|
4313
|
-
};
|
|
4314
|
-
}
|
|
4315
|
-
}
|
|
4316
|
-
);
|
|
4317
|
-
function formatWorkspaceRead(result, raw) {
|
|
4318
|
-
const body = raw ? result.content : withLineNumbers(result.content, result.startLine);
|
|
4319
|
-
if (raw) return body;
|
|
4320
|
-
return `[read_file path=${JSON.stringify(result.path)} ${workspaceReadRangeLabel(result)}${result.completeFile ? " complete" : ""}]
|
|
4321
|
-
${body || "(no lines returned)"}${workspaceReadHint(result)}`;
|
|
4322
|
-
}
|
|
4323
|
-
function workspaceReadRangeLabel(result) {
|
|
4324
|
-
const total = result.totalLines === void 0 ? "?" : String(result.totalLines);
|
|
4325
|
-
if (result.linesReturned === 0) return `lines=none totalLines=${total}`;
|
|
4326
|
-
return `lines=${result.startLine}-${result.endLine} totalLines=${total}`;
|
|
4327
|
-
}
|
|
4328
|
-
function workspaceReadHint(result) {
|
|
4329
|
-
if (result.nextStartLine === void 0 && !result.truncated) return "";
|
|
4330
|
-
const parts = [];
|
|
4331
|
-
if (result.nextStartLine !== void 0) {
|
|
4332
|
-
const nextEnd = result.nextStartLine + WORKSPACE_READ_MAX_RANGE_LINES - 1;
|
|
4333
|
-
parts.push(
|
|
4334
|
-
`next: read_file({"path":${JSON.stringify(result.path)},"startLine":${result.nextStartLine},"endLine":${nextEnd}})`
|
|
4335
|
-
);
|
|
4336
|
-
}
|
|
4337
|
-
if (result.truncationReason) parts.push(`truncated=${result.truncationReason}`);
|
|
4338
|
-
return `
|
|
4339
|
-
|
|
4340
|
-
\u2026[${parts.join("; ")}]`;
|
|
4341
|
-
}
|
|
4342
|
-
function workspaceReadRangeError(args) {
|
|
4343
|
-
const start = args.startLine ?? 1;
|
|
4344
|
-
if (args.endLine !== void 0 && args.endLine < start) {
|
|
4345
|
-
return `endLine (${args.endLine}) must be greater than or equal to startLine (${start})`;
|
|
4346
|
-
}
|
|
4347
|
-
if (args.endLine !== void 0 && args.endLine - start + 1 > WORKSPACE_READ_MAX_RANGE_LINES) {
|
|
4348
|
-
return `a read range may contain at most ${WORKSPACE_READ_MAX_RANGE_LINES} lines`;
|
|
4349
|
-
}
|
|
4350
|
-
return null;
|
|
4351
|
-
}
|
|
5085
|
+
var crossDrawerReadDependencies = {
|
|
5086
|
+
server,
|
|
5087
|
+
api,
|
|
5088
|
+
projectId,
|
|
5089
|
+
readWorkspaceFile,
|
|
5090
|
+
readWorkspaceFiles,
|
|
5091
|
+
concreteWorkspaceTarget,
|
|
5092
|
+
workspaceClient,
|
|
5093
|
+
normalizeArtifactPath,
|
|
5094
|
+
workspaceCollisionForArtifactPath,
|
|
5095
|
+
toolIsAuthorized: toolIsAuthorizedForThisSession,
|
|
5096
|
+
unwrapApiError
|
|
5097
|
+
};
|
|
5098
|
+
registerWorkspaceReadTools(crossDrawerReadDependencies);
|
|
4352
5099
|
server.tool(
|
|
4353
5100
|
"stat",
|
|
4354
5101
|
"Return metadata (kind, size, mtime) about a path in the project, or `missing` if it doesn't exist. Cheap existence probe before a write \u2014 use this to avoid accidentally overwriting a file. Mirrors Node's `fs.stat`.",
|
|
@@ -4494,6 +5241,8 @@ server.tool(
|
|
|
4494
5241
|
async ({ source, dest }) => {
|
|
4495
5242
|
const stale = await staleStepMutationResult();
|
|
4496
5243
|
if (stale) return stale;
|
|
5244
|
+
const scoped = await taskScopedWriteRefusal(dest, "workspace");
|
|
5245
|
+
if (scoped) return scoped;
|
|
4497
5246
|
try {
|
|
4498
5247
|
const result = await api.copyArtifactToWorkspace(projectId, {
|
|
4499
5248
|
source,
|
|
@@ -4846,15 +5595,12 @@ Fix the offending line(s) with replace_in_file or replace_lines \u2014 do not re
|
|
|
4846
5595
|
server.tool(
|
|
4847
5596
|
"write_file",
|
|
4848
5597
|
"Create or overwrite a file in the project. **This is how you write code** (or any workspace file) for the thing the user is building. Do NOT paste a code block into chat and expect the user to save it \u2014 that does nothing; call this tool with the full file body. If the user, task, or checker names a workspace deliverable path such as `index.html`, `report.md`, `analysis.md`, `src/solution.mjs`, `bug_report.md`, `docs/...`, or `packages/...`, call `write_file` with that exact path as soon as you have enough input to write the file. Do not write a plan, artifact, draft note, chat code block, alternate filename, or `workspace/<path>` substitute. For scratch notes or analysis material that is not meant to live in the workspace, use `write_artifact` instead. Path is relative to the project root. HTML and JS/TS files are syntax-checked before write \u2014 if the inline `<script>` or source body has a parse error, overwriting an existing file is refused and the existing file is left untouched; a broken first-write HTML draft may still be saved so you can read/repair/append instead of starting over. **For binary files (images, PDFs, audio) generated by another tool into the artifacts drawer, use `copy_artifact_to_workspace` instead of read_artifact + write_file.**",
|
|
4849
|
-
|
|
4850
|
-
path: z6.string().describe(
|
|
4851
|
-
"Exact workspace path relative to the project root. If the task names a path, pass that path exactly; do not prefix it with workspace/."
|
|
4852
|
-
),
|
|
4853
|
-
content: z6.string().describe("Full file contents.")
|
|
4854
|
-
},
|
|
5598
|
+
WriteFileInputSchema.shape,
|
|
4855
5599
|
async ({ path, content }) => {
|
|
4856
5600
|
const stale = await staleStepMutationResult();
|
|
4857
5601
|
if (stale) return stale;
|
|
5602
|
+
const scoped = await taskScopedWriteRefusal(path, "workspace");
|
|
5603
|
+
if (scoped) return scoped;
|
|
4858
5604
|
const normalizedContent = normalizeWorkspaceWriteContent(path, content);
|
|
4859
5605
|
const syntax = validateSourceContent(path, normalizedContent);
|
|
4860
5606
|
if (syntax && !syntax.ok) {
|
|
@@ -4967,16 +5713,12 @@ async function tryPersistFirstWritePartial(path, content) {
|
|
|
4967
5713
|
server.tool(
|
|
4968
5714
|
"append_to_file",
|
|
4969
5715
|
"Append text to the end of an existing file in the project. Use this to continue a `write_file` that ran out of room \u2014 wild on local models when the first call's content exceeded the per-turn output budget. Pass the path and ONLY the missing tail (the parts of the file you haven't written yet); the existing content stays. For a brand-new file, prefer `write_file`. Path is relative to the project root.",
|
|
4970
|
-
|
|
4971
|
-
path: z6.string().describe("File path relative to the project root."),
|
|
4972
|
-
content: z6.string().describe("Text to append to the end of the file."),
|
|
4973
|
-
create: z6.boolean().optional().describe(
|
|
4974
|
-
"When true, create the file (with the given content as its only contents) if it does not yet exist. Default false \u2014 refuse to append to a missing file."
|
|
4975
|
-
)
|
|
4976
|
-
},
|
|
5716
|
+
AppendToFileInputSchema.shape,
|
|
4977
5717
|
async ({ path, content, create }) => {
|
|
4978
5718
|
const stale = await staleStepMutationResult();
|
|
4979
5719
|
if (stale) return stale;
|
|
5720
|
+
const scoped = await taskScopedWriteRefusal(path, "workspace");
|
|
5721
|
+
if (scoped) return scoped;
|
|
4980
5722
|
try {
|
|
4981
5723
|
let prior = "";
|
|
4982
5724
|
try {
|
|
@@ -5028,18 +5770,14 @@ server.tool(
|
|
|
5028
5770
|
server.tool(
|
|
5029
5771
|
"replace_in_file",
|
|
5030
5772
|
"Make a surgical edit to an existing file by replacing one literal substring with another. **Strongly preferred over `write_file` for editing any file that already exists** \u2014 token cost is proportional to the change, not the file size, and you don't risk re-truncating a long file you already wrote correctly. `find` is matched verbatim (no regex). By default the pattern must match exactly once; pass `occurrence: 'all'` to apply blanket renames, or a 1-based index to target a specific match. Returns a unified diff so you can verify what changed. If `find` isn't unique you'll get back an `ambiguous-match` error \u2014 re-read the file and use a longer literal substring.",
|
|
5031
|
-
{
|
|
5032
|
-
path: z6.string().describe("File path relative to the project root."),
|
|
5033
|
-
find: z6.string().min(1).describe("Literal substring to find. No regex. Match is whitespace-exact."),
|
|
5034
|
-
replace: z6.string().describe("New content for the matched region. May be empty to delete."),
|
|
5035
|
-
occurrence: z6.union([z6.number().int().positive(), z6.literal("all")]).optional().describe(
|
|
5036
|
-
"Default: exactly one match required. Pass a 1-based index for the Nth match, or 'all' to replace every occurrence."
|
|
5037
|
-
),
|
|
5773
|
+
ReplaceInFileInputSchema.extend({
|
|
5038
5774
|
partial: PartialEditArg
|
|
5039
|
-
},
|
|
5775
|
+
}).shape,
|
|
5040
5776
|
async ({ path, find, replace, occurrence, partial }) => {
|
|
5041
5777
|
const stale = await staleStepMutationResult();
|
|
5042
5778
|
if (stale) return stale;
|
|
5779
|
+
const scoped = await taskScopedWriteRefusal(path, "workspace");
|
|
5780
|
+
if (scoped) return scoped;
|
|
5043
5781
|
try {
|
|
5044
5782
|
const target = await concreteWorkspaceTarget(path);
|
|
5045
5783
|
const targetApi = editClient(target);
|
|
@@ -5089,18 +5827,14 @@ server.tool(
|
|
|
5089
5827
|
server.tool(
|
|
5090
5828
|
"replace_lines",
|
|
5091
5829
|
"Replace an inclusive range of lines in an existing file with new content \u2014 the easiest surgical edit when you know *which lines* are wrong (e.g. `read_file` shows `142\u2192` gutters, or `validate`/`write_file` reported a parse error 'at line 142'). You just give `startLine`/`endLine` and the replacement `content`; no need to reproduce an exact `find` string or count diff coordinates. To replace one line, set `startLine === endLine`. To delete lines, pass an empty `content`. **Do NOT include the `N\u2192` line-number gutter in `content`** \u2014 that's a display aid, not file text. **Each edit shifts the lines below it**, so line numbers from an earlier `read_file` go stale after the first edit; this tool reports the shift and re-prints the edited region with fresh numbers, so target your next edit from that, not from the original read.",
|
|
5092
|
-
{
|
|
5093
|
-
path: z6.string().describe("File path relative to the project root."),
|
|
5094
|
-
startLine: z6.number().int().positive().describe("1-based first line to replace (inclusive). Read it from the read_file gutter."),
|
|
5095
|
-
endLine: z6.number().int().positive().describe(
|
|
5096
|
-
"1-based last line to replace (inclusive). Equal to startLine to replace one line."
|
|
5097
|
-
),
|
|
5098
|
-
content: z6.string().describe("Replacement text for the range. Empty deletes the lines. No `N\u2192` gutter."),
|
|
5830
|
+
ReplaceLinesInputSchema.extend({
|
|
5099
5831
|
partial: PartialEditArg
|
|
5100
|
-
},
|
|
5832
|
+
}).shape,
|
|
5101
5833
|
async ({ path, startLine, endLine, content, partial }) => {
|
|
5102
5834
|
const stale = await staleStepMutationResult();
|
|
5103
5835
|
if (stale) return stale;
|
|
5836
|
+
const scoped = await taskScopedWriteRefusal(path, "workspace");
|
|
5837
|
+
if (scoped) return scoped;
|
|
5104
5838
|
try {
|
|
5105
5839
|
const target = await concreteWorkspaceTarget(path);
|
|
5106
5840
|
const targetApi = editClient(target);
|
|
@@ -5167,6 +5901,8 @@ server.tool(
|
|
|
5167
5901
|
async ({ path, diff, partial }) => {
|
|
5168
5902
|
const stale = await staleStepMutationResult();
|
|
5169
5903
|
if (stale) return stale;
|
|
5904
|
+
const scoped = await taskScopedWriteRefusal(path, "workspace");
|
|
5905
|
+
if (scoped) return scoped;
|
|
5170
5906
|
try {
|
|
5171
5907
|
const target = await concreteWorkspaceTarget(path);
|
|
5172
5908
|
const targetApi = editClient(target);
|
|
@@ -5224,6 +5960,8 @@ server.tool(
|
|
|
5224
5960
|
async ({ path, marker, content, where, partial }) => {
|
|
5225
5961
|
const stale = await staleStepMutationResult();
|
|
5226
5962
|
if (stale) return stale;
|
|
5963
|
+
const scoped = await taskScopedWriteRefusal(path, "workspace");
|
|
5964
|
+
if (scoped) return scoped;
|
|
5227
5965
|
try {
|
|
5228
5966
|
const target = await concreteWorkspaceTarget(path);
|
|
5229
5967
|
const targetApi = editClient(target);
|
|
@@ -5280,6 +6018,8 @@ server.tool(
|
|
|
5280
6018
|
async ({ path, recursive }) => {
|
|
5281
6019
|
const stale = await staleStepMutationResult();
|
|
5282
6020
|
if (stale) return stale;
|
|
6021
|
+
const scoped = await taskScopedWriteRefusal(path, "workspace");
|
|
6022
|
+
if (scoped) return scoped;
|
|
5283
6023
|
try {
|
|
5284
6024
|
const target = await concreteWorkspaceTarget(path);
|
|
5285
6025
|
await editClient(target).rmProjectWorkspacePath(target.projectId, target.path, {
|
|
@@ -5305,6 +6045,8 @@ server.tool(
|
|
|
5305
6045
|
async ({ path }) => {
|
|
5306
6046
|
const stale = await staleStepMutationResult();
|
|
5307
6047
|
if (stale) return stale;
|
|
6048
|
+
const scoped = await taskScopedWriteRefusal(path, "workspace");
|
|
6049
|
+
if (scoped) return scoped;
|
|
5308
6050
|
try {
|
|
5309
6051
|
const target = await concreteWorkspaceTarget(path);
|
|
5310
6052
|
await workspaceClient(target).mkdirProjectWorkspace(target.projectId, {
|
|
@@ -5331,6 +6073,10 @@ server.tool(
|
|
|
5331
6073
|
async ({ fromPath, toPath }) => {
|
|
5332
6074
|
const stale = await staleStepMutationResult();
|
|
5333
6075
|
if (stale) return stale;
|
|
6076
|
+
const scoped1 = await taskScopedWriteRefusal(fromPath, "workspace");
|
|
6077
|
+
if (scoped1) return scoped1;
|
|
6078
|
+
const scoped2 = await taskScopedWriteRefusal(toPath, "workspace");
|
|
6079
|
+
if (scoped2) return scoped2;
|
|
5334
6080
|
try {
|
|
5335
6081
|
const [fromTarget, toTarget] = await Promise.all([
|
|
5336
6082
|
concreteWorkspaceTarget(fromPath),
|
|
@@ -5909,15 +6655,10 @@ async function workspaceCollisionForArtifactPath(cleanPath) {
|
|
|
5909
6655
|
}
|
|
5910
6656
|
return null;
|
|
5911
6657
|
}
|
|
5912
|
-
|
|
5913
|
-
|
|
5914
|
-
|
|
5915
|
-
|
|
5916
|
-
const result = await api.readProjectArtifactSlice(projectId, cleanPath, { head: 0 });
|
|
5917
|
-
return result.kind === "found" && !result.fuzzy ? result.path : null;
|
|
5918
|
-
} catch {
|
|
5919
|
-
return null;
|
|
5920
|
-
}
|
|
6658
|
+
function toolIsAuthorizedForThisSession(name) {
|
|
6659
|
+
const canonical = canonicalToolName(name);
|
|
6660
|
+
if (authorizedToolNames !== null) return authorizedToolNames.has(canonical);
|
|
6661
|
+
return !excludedToolNames.has(canonical) && (allowedToolNames === null || allowedToolNames.has(canonical));
|
|
5921
6662
|
}
|
|
5922
6663
|
var WORKSPACE_DELIVERABLE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
5923
6664
|
"html",
|
|
@@ -5970,19 +6711,15 @@ async function listWorkspaceDeliverableFiles(projectId2) {
|
|
|
5970
6711
|
server.tool(
|
|
5971
6712
|
"list_artifacts",
|
|
5972
6713
|
'List files in the project artifacts folder, recursively across all subdirectories. Use this when handing work off between gezels \u2014 anything a teammate produced will show up here regardless of how deeply they nested it. A task\'s working files live under its own folder, `tasks/<num>/`. Pass `path` to walk one subtree only (large drawers are capped, so scoping is how you see every file in a corpus); pass `recursive: false` for a one-level listing. Returned paths are relative to the artifacts root and can be read as-is \u2014 do NOT prefix with "artifacts/".',
|
|
5973
|
-
|
|
5974
|
-
path: z6.string().optional().describe(
|
|
5975
|
-
'Subdirectory to walk (default: the whole artifacts root). Scopes recursive listings too. Do not include "artifacts/" \u2014 the call is already scoped there.'
|
|
5976
|
-
),
|
|
5977
|
-
recursive: z6.boolean().optional().describe(
|
|
5978
|
-
"Walk all subdirectories (default: true). Set to false for a single-level listing."
|
|
5979
|
-
)
|
|
5980
|
-
},
|
|
6714
|
+
ListArtifactsInputSchema.shape,
|
|
5981
6715
|
async ({ path, recursive }) => {
|
|
5982
6716
|
const subpath = normalizeArtifactPath(path ?? "");
|
|
5983
6717
|
const wantRecursive = recursive !== false;
|
|
5984
6718
|
const res = await api.listProjectArtifacts(projectId, subpath || void 0, wantRecursive);
|
|
5985
|
-
const listing = res.files.map(
|
|
6719
|
+
const listing = res.files.map(
|
|
6720
|
+
(f) => f.isDirectory ? `\u{1F4C1} ${f.path}` : `\u{1F4C4} ${f.path}
|
|
6721
|
+
open: ${renderExactToolCall("read_artifact", { path: f.path })}`
|
|
6722
|
+
).join("\n");
|
|
5986
6723
|
const summary = res.files.length ? `Listed ${res.files.length} ${res.files.length === 1 ? "artifact entry" : "artifact entries"}${subpath ? ` under ${subpath}/` : ""}.` : subpath ? `No artifacts under ${subpath}/.` : "No artifacts yet.";
|
|
5987
6724
|
const truncation = res.truncated ? `
|
|
5988
6725
|
Results were truncated; ${subpath ? "narrow `path` further" : "pass `path` to scope the walk"} or use \`recursive: false\`.` : "";
|
|
@@ -5990,7 +6727,11 @@ Results were truncated; ${subpath ? "narrow `path` further" : "pass `path` to sc
|
|
|
5990
6727
|
ListToolOutputSchema,
|
|
5991
6728
|
{
|
|
5992
6729
|
summary,
|
|
5993
|
-
items: res.files
|
|
6730
|
+
items: res.files.map((file) => ({
|
|
6731
|
+
...file,
|
|
6732
|
+
surface: "artifact",
|
|
6733
|
+
...!file.isDirectory ? { readWith: "read_artifact" } : {}
|
|
6734
|
+
})),
|
|
5994
6735
|
count: res.files.length,
|
|
5995
6736
|
...res.truncated !== void 0 ? { truncated: res.truncated } : {}
|
|
5996
6737
|
},
|
|
@@ -5999,84 +6740,7 @@ ${listing}${truncation}` : `${summary}${truncation}` }
|
|
|
5999
6740
|
);
|
|
6000
6741
|
}
|
|
6001
6742
|
);
|
|
6002
|
-
|
|
6003
|
-
"read_artifact",
|
|
6004
|
-
'Read a file from the artifacts drawer only (a report, script, or output returned by `list_artifacts` or explicitly described as an artifact). Not for workspace files shown under "Workspace files" \u2014 use `read_file` for those. Accepts a full path relative to the artifacts root ("reports/summary.md") or just a basename ("summary.md") \u2014 if exact misses, falls back to a case-insensitive basename search. Optional slice params for navigating large artifacts (e.g. `auto/browser_snapshot/...` files persisted by the outboard-storage wrapper): `lines: { start, count }` for a 1-indexed line range, `head: N` for the first N lines, `tail: N` for the last N. At most one slice param; omit all to get the full content. Result includes `totalLines` / `hasMore` so you can paginate without guessing.',
|
|
6005
|
-
{
|
|
6006
|
-
path: z6.string().describe(
|
|
6007
|
-
'File path or basename. A redundant "artifacts/" prefix is stripped automatically.'
|
|
6008
|
-
),
|
|
6009
|
-
lines: z6.object({
|
|
6010
|
-
start: z6.number().int().min(1).describe("1-indexed first line to return."),
|
|
6011
|
-
count: z6.number().int().min(0).describe("Number of lines to return.")
|
|
6012
|
-
}).optional().describe("Read a specific line range (mutually exclusive with `head` / `tail`)."),
|
|
6013
|
-
head: z6.number().int().min(0).optional().describe("Read just the first N lines."),
|
|
6014
|
-
tail: z6.number().int().min(0).optional().describe("Read just the last N lines.")
|
|
6015
|
-
},
|
|
6016
|
-
async ({ path, lines, head, tail }) => {
|
|
6017
|
-
const opts = {};
|
|
6018
|
-
if (lines) opts.lines = lines;
|
|
6019
|
-
else if (typeof head === "number") opts.head = head;
|
|
6020
|
-
else if (typeof tail === "number") opts.tail = tail;
|
|
6021
|
-
const clean = normalizeArtifactPath(path);
|
|
6022
|
-
const res = await api.readProjectArtifactSlice(projectId, clean, opts);
|
|
6023
|
-
if (res.kind === "missing") {
|
|
6024
|
-
const workspaceCollision = await workspaceCollisionForArtifactPath(clean);
|
|
6025
|
-
if (workspaceCollision) {
|
|
6026
|
-
const tool = workspaceCollision.kind === "dir" ? "list_dir" : "read_file";
|
|
6027
|
-
return {
|
|
6028
|
-
content: [
|
|
6029
|
-
{
|
|
6030
|
-
type: "text",
|
|
6031
|
-
text: `Artifact "${path}" not found, but a workspace ${workspaceCollision.kind} exists at "${workspaceCollision.path}". Use ${tool}({ path: "${workspaceCollision.path}" }) instead of read_artifact if that tool is available, or delegate to a gezel with workspace read access.`
|
|
6032
|
-
}
|
|
6033
|
-
],
|
|
6034
|
-
isError: true
|
|
6035
|
-
};
|
|
6036
|
-
}
|
|
6037
|
-
return {
|
|
6038
|
-
content: [
|
|
6039
|
-
{
|
|
6040
|
-
type: "text",
|
|
6041
|
-
text: `Artifact "${path}" not found. Call list_artifacts to see what's available.`
|
|
6042
|
-
}
|
|
6043
|
-
],
|
|
6044
|
-
isError: true
|
|
6045
|
-
};
|
|
6046
|
-
}
|
|
6047
|
-
if (res.kind === "ambiguous") {
|
|
6048
|
-
return {
|
|
6049
|
-
content: [
|
|
6050
|
-
{
|
|
6051
|
-
type: "text",
|
|
6052
|
-
text: `"${path}" matches multiple artifacts. Call read_artifact again with a full path:
|
|
6053
|
-
${res.candidates.map((p) => ` \u2022 ${p}`).join("\n")}`
|
|
6054
|
-
}
|
|
6055
|
-
],
|
|
6056
|
-
isError: true
|
|
6057
|
-
};
|
|
6058
|
-
}
|
|
6059
|
-
const header = res.fuzzy ? `(matched ${res.path} by basename)
|
|
6060
|
-
` : "";
|
|
6061
|
-
const sliceTail = res.hasMore || res.linesReturned !== res.totalLines ? `
|
|
6062
|
-
|
|
6063
|
-
\u2026[lines ${res.linesReturned} of ${res.totalLines}; ${res.hasMore ? "more available" : "this is the last slice"}. Re-call with \`lines: { start, count }\` to read more.]` : "";
|
|
6064
|
-
return {
|
|
6065
|
-
content: [{ type: "text", text: header + res.content + sliceTail }],
|
|
6066
|
-
structuredContent: {
|
|
6067
|
-
requestedPath: clean,
|
|
6068
|
-
resolvedPath: res.path,
|
|
6069
|
-
fuzzy: res.fuzzy,
|
|
6070
|
-
// Hosts may prefer structuredContent over the text blocks. Both forms
|
|
6071
|
-
// must carry the requested slice, not just its lookup metadata.
|
|
6072
|
-
content: res.content,
|
|
6073
|
-
linesReturned: res.linesReturned,
|
|
6074
|
-
totalLines: res.totalLines,
|
|
6075
|
-
hasMore: res.hasMore
|
|
6076
|
-
}
|
|
6077
|
-
};
|
|
6078
|
-
}
|
|
6079
|
-
);
|
|
6743
|
+
registerArtifactReadTools(crossDrawerReadDependencies);
|
|
6080
6744
|
server.tool(
|
|
6081
6745
|
"grep_artifact",
|
|
6082
6746
|
"Regex-search a single artifact and return matched lines (with optional surrounding context). Use this when you saved a large output to artifacts (e.g. a `browser_snapshot` or `fetch_url` summary that includes a path) and need to find specific data without pulling the whole file back through. Pattern is a JS regex source string; case-insensitive by default. `contextLines` adds N surrounding lines per match. `maxMatches` caps the result so a runaway `.*` pattern can't dump the whole file.",
|
|
@@ -6099,16 +6763,35 @@ server.tool(
|
|
|
6099
6763
|
if (res.kind === "missing") {
|
|
6100
6764
|
const workspaceCollision = await workspaceCollisionForArtifactPath(clean);
|
|
6101
6765
|
if (workspaceCollision) {
|
|
6102
|
-
const
|
|
6103
|
-
|
|
6104
|
-
|
|
6105
|
-
|
|
6106
|
-
|
|
6107
|
-
|
|
6108
|
-
|
|
6109
|
-
|
|
6110
|
-
|
|
6111
|
-
|
|
6766
|
+
const workspaceArgs = equivalentWorkspaceGrepArgs(workspaceCollision.path, pattern, {
|
|
6767
|
+
caseInsensitive,
|
|
6768
|
+
contextLines,
|
|
6769
|
+
maxMatches
|
|
6770
|
+
});
|
|
6771
|
+
const exactCall = renderExactToolCall("grep_files", workspaceArgs);
|
|
6772
|
+
if (toolIsAuthorizedForThisSession("grep_files")) {
|
|
6773
|
+
try {
|
|
6774
|
+
const workspaceResult = await api.toolSearchFiles(projectId, workspaceArgs);
|
|
6775
|
+
return workspaceGrepResult(
|
|
6776
|
+
workspaceArgs,
|
|
6777
|
+
workspaceResult,
|
|
6778
|
+
`Rerouted grep_artifact to the equivalent workspace call because "${path}" is a workspace ${workspaceCollision.kind}, not an artifact:
|
|
6779
|
+
${exactCall}`
|
|
6780
|
+
);
|
|
6781
|
+
} catch (err) {
|
|
6782
|
+
return errorResult(
|
|
6783
|
+
`Artifact "${path}" was not found and its automatic workspace fallback failed: ${unwrapApiError(err)}`,
|
|
6784
|
+
{ retryable: true, hint: exactCall }
|
|
6785
|
+
);
|
|
6786
|
+
}
|
|
6787
|
+
}
|
|
6788
|
+
return errorResult(
|
|
6789
|
+
`Artifact "${path}" not found, but a workspace ${workspaceCollision.kind} exists at "${workspaceCollision.path}". grep_files is not authorized for this session.`,
|
|
6790
|
+
{
|
|
6791
|
+
retryable: false,
|
|
6792
|
+
hint: `Delegate to a gezel with workspace search access to run ${exactCall}`
|
|
6793
|
+
}
|
|
6794
|
+
);
|
|
6112
6795
|
}
|
|
6113
6796
|
return {
|
|
6114
6797
|
content: [
|
|
@@ -6302,18 +6985,24 @@ ${res.candidates.map((p) => ` \u2022 ${p}`).join("\n")}`
|
|
|
6302
6985
|
server.tool(
|
|
6303
6986
|
"write_artifact",
|
|
6304
6987
|
"Create or update a file in the project's **artifacts** folder \u2014 the side drawer for supporting material (reports, plans, analysis, research, scratch notes). **NOT for the app's source code** \u2014 use `write_file` for that. Artifacts live in a separate folder so the user can distinguish your working notes from the code/content you ship. When working a task, its working files belong in that task's folder, `tasks/<num>/` (e.g. `tasks/11/outline.md`). Calls that target an existing workspace path are refused unless `force: true` is set; source-code extensions (.tsx, .css, .html, .py, \u2026) outside the canonical `tasks/`/`scripts/`/`tests/`/`mocks/`/`drafts/` folders are automatically redirected into the workspace with `write_file` semantics.",
|
|
6305
|
-
{
|
|
6306
|
-
path: z6.string().describe(
|
|
6307
|
-
'File path relative to the artifacts root (e.g. "summary.md" or "reports/summary.md"). Do NOT prefix with "artifacts/" \u2014 the call is already scoped there.'
|
|
6308
|
-
),
|
|
6309
|
-
content: z6.string().describe("File content to write"),
|
|
6988
|
+
WriteArtifactInputSchema.extend({
|
|
6310
6989
|
force: z6.boolean().optional().describe(
|
|
6311
6990
|
"Bypass the workspace-collision and source-code-extension guards. Only set when you deliberately want to stash a code-looking file in artifacts (rare \u2014 a mock, a scratch experiment you're not shipping)."
|
|
6312
6991
|
)
|
|
6313
|
-
},
|
|
6314
|
-
async ({ path, content, force }) => {
|
|
6992
|
+
}).shape,
|
|
6993
|
+
async ({ path, content: rawContent, jsonContent, force }) => {
|
|
6315
6994
|
const stale = await staleStepMutationResult();
|
|
6316
6995
|
if (stale) return stale;
|
|
6996
|
+
const scoped = await taskScopedWriteRefusal(path, "artifacts");
|
|
6997
|
+
if (scoped) return scoped;
|
|
6998
|
+
if (rawContent === void 0 === (jsonContent === void 0)) {
|
|
6999
|
+
return errorResult(
|
|
7000
|
+
"Supply exactly one of content or jsonContent. Use jsonContent for a structured JSON report."
|
|
7001
|
+
);
|
|
7002
|
+
}
|
|
7003
|
+
const value = jsonContent ?? rawContent;
|
|
7004
|
+
const content = typeof value === "string" ? value : `${JSON.stringify(value, null, 2)}
|
|
7005
|
+
`;
|
|
6317
7006
|
const clean = normalizeArtifactPath(path);
|
|
6318
7007
|
if (isReservedShadowArtifactPath(clean)) {
|
|
6319
7008
|
return {
|
|
@@ -6420,7 +7109,17 @@ server.tool(
|
|
|
6420
7109
|
...gezelId ? { gezelId } : {},
|
|
6421
7110
|
...sessionId ? { sessionId } : {}
|
|
6422
7111
|
});
|
|
6423
|
-
|
|
7112
|
+
let completionHint = "";
|
|
7113
|
+
if (sessionTaskRef && sessionStepId) {
|
|
7114
|
+
if (sessionStepCompletion === "automatic") {
|
|
7115
|
+
completionHint = "\nThis step uses automatic completion checks. Finish its required deliverable and stop; the runtime will run its completion gate. Saving does not approve the work. If the gate rejects it, repair the named problems and save the complete deliverable again.";
|
|
7116
|
+
} else if (sessionStepCompletion === "manual") {
|
|
7117
|
+
completionHint = "\nSaving an artifact does not complete the task step. When its required deliverable is ready, call advance_task_step to run the completion checks. Repair specific failures if returned; do not repeatedly rewrite a finished report without submitting it.";
|
|
7118
|
+
} else {
|
|
7119
|
+
completionHint = "\nFollow the active craftbook completion rule. If it uses automatic completion, finish the required deliverable and stop; otherwise call advance_task_step when ready. Saving alone is not approval. Repair any specific validation failures returned.";
|
|
7120
|
+
}
|
|
7121
|
+
}
|
|
7122
|
+
return { content: [{ type: "text", text: `Wrote ${clean}${completionHint}` }] };
|
|
6424
7123
|
}
|
|
6425
7124
|
);
|
|
6426
7125
|
server.tool(
|
|
@@ -6477,10 +7176,7 @@ ${listing}` : summary }
|
|
|
6477
7176
|
server.tool(
|
|
6478
7177
|
"list_documents",
|
|
6479
7178
|
"List files in the shared documents library \u2014 cross-project guides every gezel can read (guidelines, mission statements, style guides, policies). Pass { recursive: true } to see inside folders. To find content rather than names, use search_documents.",
|
|
6480
|
-
|
|
6481
|
-
path: z6.string().optional().describe("Subdirectory path to list (default: root)"),
|
|
6482
|
-
recursive: z6.boolean().optional().describe("List all descendants (default: false)")
|
|
6483
|
-
},
|
|
7179
|
+
ListDocumentsInputSchema.shape,
|
|
6484
7180
|
async ({ path, recursive }) => {
|
|
6485
7181
|
const res = await api.listDocuments(path ?? "", recursive ?? false);
|
|
6486
7182
|
const listing = res.files.map((f) => `${f.isDirectory ? "dir " : "file"} ${f.path}`).join("\n");
|
|
@@ -6496,11 +7192,7 @@ ${listing}` : summary }
|
|
|
6496
7192
|
server.tool(
|
|
6497
7193
|
"read_document",
|
|
6498
7194
|
"Read one document from the shared library by path, or a knowledge-catalog article by its knowledge:// URI (from a `search` result with the knowledge source). Office documents (.docx, .pdf, .pptx, .xlsx) come back converted to markdown. Get paths from the library listing, list_documents, or a search_documents match.",
|
|
6499
|
-
|
|
6500
|
-
path: z6.string().describe(
|
|
6501
|
-
'File path relative to the documents root (e.g. "guidelines/coding.md"), or a knowledge:// URI (e.g. "knowledge://world-history/1234#line=10-40")'
|
|
6502
|
-
)
|
|
6503
|
-
},
|
|
7195
|
+
ReadDocumentInputSchema.shape,
|
|
6504
7196
|
async ({ path }) => {
|
|
6505
7197
|
const knowledgeUri = parseKnowledgeUri(path);
|
|
6506
7198
|
if (knowledgeUri) {
|
|
@@ -6528,10 +7220,7 @@ ${body}` }] };
|
|
|
6528
7220
|
server.tool(
|
|
6529
7221
|
"write_document",
|
|
6530
7222
|
'Create or update a document in the shared documents library (markdown preferred). Use for durable cross-project knowledge \u2014 guidelines, policies, style rules. For knowledge specific to one project, use a folder named after that project (e.g. "acme-site/decisions.md"). Deliverables for the current job belong in the workspace or artifacts, not here.',
|
|
6531
|
-
|
|
6532
|
-
path: z6.string().describe('File path relative to the documents root (e.g. "guidelines/coding.md")'),
|
|
6533
|
-
content: z6.string().describe("File content to write (markdown recommended)")
|
|
6534
|
-
},
|
|
7223
|
+
WriteDocumentInputSchema.shape,
|
|
6535
7224
|
async ({ path, content }) => {
|
|
6536
7225
|
const redirected = await redirectExpectedDeliverableWriteToWorkspace(
|
|
6537
7226
|
path,
|
|
@@ -6588,7 +7277,7 @@ ${lines.join("\n")}` : summary }
|
|
|
6588
7277
|
server.tool(
|
|
6589
7278
|
"list_gezels",
|
|
6590
7279
|
"List every gezel (agent) on the user's team. Each entry includes id, name, and role. Use this to find the right gezel for a task, or to see who needs a change.",
|
|
6591
|
-
|
|
7280
|
+
EmptyInputSchema.shape,
|
|
6592
7281
|
async () => {
|
|
6593
7282
|
const res = await api.listGezels();
|
|
6594
7283
|
const listing = res.gezels.map(
|
|
@@ -6655,7 +7344,7 @@ server.tool(
|
|
|
6655
7344
|
server.tool(
|
|
6656
7345
|
"list_gilde",
|
|
6657
7346
|
'List the gezel templates ("gilde" \u2014 the guild roster) bundled with Gezel. Each template has a canonical role and curated about.md. For normal recruitment call ensure_gezel with the role; to force a separate new gezel from an exact template, call create_gezel with templateId.',
|
|
6658
|
-
|
|
7347
|
+
EmptyInputSchema.shape,
|
|
6659
7348
|
async () => {
|
|
6660
7349
|
const res = await api.listCatalogItems("gezel-template");
|
|
6661
7350
|
if (!res.items.length) {
|
|
@@ -6697,12 +7386,14 @@ server.tool(
|
|
|
6697
7386
|
typeId,
|
|
6698
7387
|
...params ? { params } : {}
|
|
6699
7388
|
});
|
|
6700
|
-
const gz = applied.gezelsCreated.map(
|
|
7389
|
+
const gz = applied.gezelsCreated.map(
|
|
7390
|
+
(g) => `${g.name}${g.voorman ? " (voorman)" : ""}${g.reused ? " (already on the crew)" : ""}`
|
|
7391
|
+
).join(", ");
|
|
6701
7392
|
return {
|
|
6702
7393
|
content: [
|
|
6703
7394
|
{
|
|
6704
7395
|
type: "text",
|
|
6705
|
-
text: `Applied project type ${applied.typeId}@${applied.version} to ${resolvedProject}.
|
|
7396
|
+
text: `Applied project type ${applied.typeId}@${applied.version} to ${resolvedProject}. Crew: ${gz || "no gezels"}. Installed ${applied.scriptsInstalled.length} script(s); seeded ${applied.workspaceSeeded.length} file(s).`
|
|
6706
7397
|
}
|
|
6707
7398
|
]
|
|
6708
7399
|
};
|
|
@@ -6905,10 +7596,6 @@ function craftbookSetupRequiredText(craftbookId, missing) {
|
|
|
6905
7596
|
}).join(", ");
|
|
6906
7597
|
return `SETUP REQUIRED for craftbook "${craftbookId}": install/configure ${needs} from the project's Craftbooks/Commands setup before invoking it. Do not create a substitute task, hand-write replacement steps, or silently change the requested output format.`;
|
|
6907
7598
|
}
|
|
6908
|
-
function normalizedCraftbookTaskDescription(description, craftbookId) {
|
|
6909
|
-
const text = description?.trim() || `Run the ${craftbookId} craftbook against this project.`;
|
|
6910
|
-
return text.length >= 40 ? text : `${text} Complete every gated production and review step.`;
|
|
6911
|
-
}
|
|
6912
7599
|
async function autoInstallTrustedCraftbookToolsets(project, requirements) {
|
|
6913
7600
|
const installed = [];
|
|
6914
7601
|
const scope = { kind: "project", projectId: project };
|
|
@@ -6997,13 +7684,23 @@ async function currentRootTurnContext() {
|
|
|
6997
7684
|
try {
|
|
6998
7685
|
const session = await api.getChatSession(sessionId);
|
|
6999
7686
|
const rootTurnId = rootTurnIdFromMessages(sessionId, session.messages);
|
|
7000
|
-
if (!rootTurnId)
|
|
7687
|
+
if (!rootTurnId) {
|
|
7688
|
+
process.stderr.write(
|
|
7689
|
+
`[mcp] root-turn dedupe unavailable: session ${sessionId} has no user message among ${session.messages.length}
|
|
7690
|
+
`
|
|
7691
|
+
);
|
|
7692
|
+
return null;
|
|
7693
|
+
}
|
|
7001
7694
|
const latestUser = [...session.messages].reverse().find((message) => message.role === "user");
|
|
7002
7695
|
return {
|
|
7003
7696
|
rootTurnId,
|
|
7004
7697
|
...latestUser?.content.trim() ? { userText: latestUser.content.trim() } : {}
|
|
7005
7698
|
};
|
|
7006
|
-
} catch {
|
|
7699
|
+
} catch (err) {
|
|
7700
|
+
process.stderr.write(
|
|
7701
|
+
`[mcp] root-turn dedupe unavailable: cannot read session ${sessionId}: ${err instanceof Error ? err.message : String(err)}
|
|
7702
|
+
`
|
|
7703
|
+
);
|
|
7007
7704
|
return null;
|
|
7008
7705
|
}
|
|
7009
7706
|
}
|
|
@@ -7032,22 +7729,24 @@ async function launchCraftbookTask(args) {
|
|
|
7032
7729
|
}
|
|
7033
7730
|
if (missing.length > 0) return { kind: "setup-required", missing, installed };
|
|
7034
7731
|
if (args.dedupeActiveCraftbook) {
|
|
7732
|
+
const outputPath = args.params?.outputPath;
|
|
7035
7733
|
const active = (await api.listProjectTasks(args.project)).tasks.find(
|
|
7036
|
-
(task2) => task2.craftbook.id === args.craftbookId && (task2.status === "draft" || task2.status === "active" || task2.status === "paused")
|
|
7734
|
+
(task2) => task2.craftbook.id === args.craftbookId && (task2.status === "draft" || task2.status === "active" || task2.status === "paused") && (outputPath === void 0 || task2.craftbookParams?.outputPath === outputPath)
|
|
7037
7735
|
);
|
|
7038
7736
|
if (active) return { kind: "existing", task: active, installed };
|
|
7039
7737
|
}
|
|
7040
7738
|
const craftbookName = projectCraftbooks.items.find((item) => item.manifest.id === args.craftbookId)?.manifest.name ?? args.craftbookId;
|
|
7041
|
-
const effectiveParams =
|
|
7739
|
+
const { description, params: effectiveParams } = composeCraftbookLaunch({
|
|
7740
|
+
...args.description !== void 0 ? { message: args.description } : {},
|
|
7741
|
+
craftbookName,
|
|
7042
7742
|
paramSchema: declaredCraftbook?.manifest.kind === "craftbook-template" ? declaredCraftbook.manifest.paramSchema : void 0,
|
|
7043
|
-
params: args.params
|
|
7044
|
-
jobDescription: args.description
|
|
7743
|
+
...args.params ? { params: args.params } : {}
|
|
7045
7744
|
});
|
|
7046
7745
|
const resolvedAssignee = await resolveAssigneeArg(args.assignee);
|
|
7047
7746
|
const task = await api.createTask(args.project, {
|
|
7048
7747
|
...sessionTaskNamingMode,
|
|
7049
7748
|
title: args.title ?? craftbookName,
|
|
7050
|
-
description
|
|
7749
|
+
description,
|
|
7051
7750
|
craftbookId: args.craftbookId,
|
|
7052
7751
|
...args.version ? { craftbookVersion: args.version } : {},
|
|
7053
7752
|
...Object.keys(effectiveParams).length > 0 ? { craftbookParams: effectiveParams } : {},
|
|
@@ -7851,11 +8550,7 @@ server.tool(
|
|
|
7851
8550
|
server.tool(
|
|
7852
8551
|
"ensure_gezel",
|
|
7853
8552
|
"Make sure a gezel exists who can handle a given job (designer, dev, copywriter, \u2026) and return them, creating one if nothing fits. Prefer this over the `list_gezels` \u2192 `list_gilde` \u2192 `create_gezel` sequence: one fuzzy, idempotent call reuses a good roster match or creates from the matching gilde template. Gezels are shared across projects, so reuse preserves their memory of the user's preferences. Use `create_gezel` only when you explicitly need a separate new gezel, an exact templateId, or a custom about.md.",
|
|
7854
|
-
|
|
7855
|
-
jobTitle: z6.string().describe(
|
|
7856
|
-
'The role you need filled \u2014 "designer", "dev", "UX researcher", "copywriter", etc. Fuzzy-matched against the roster + templates.'
|
|
7857
|
-
)
|
|
7858
|
-
},
|
|
8553
|
+
EnsureGezelInputSchema.shape,
|
|
7859
8554
|
async ({ jobTitle }) => {
|
|
7860
8555
|
const res = await api.ensureGezel({
|
|
7861
8556
|
jobTitle
|
|
@@ -7863,11 +8558,11 @@ server.tool(
|
|
|
7863
8558
|
const headline = res.action === "reused" ? `Reused ${res.name} (${res.role}) \u2014 existing gezel, match score ${res.matchScore?.toFixed(2) ?? "?"}` : res.action === "created-from-gilde" ? `Created ${res.name} from the "${res.templateId}" gilde template` : `Created ${res.name} (${res.role}) with a bespoke about.md`;
|
|
7864
8559
|
const tail = res.alternatives && res.alternatives.length > 0 ? `
|
|
7865
8560
|
Runner-ups on the roster: ${res.alternatives.join(", ")}. If ${res.name} is wrong, pass a more specific \`jobTitle\` next time.` : "";
|
|
7866
|
-
const projectArgFragment =
|
|
7867
|
-
const projectArgGuidance = projectId === "default" ?
|
|
8561
|
+
const projectArgFragment = `, project: "${projectId}"`;
|
|
8562
|
+
const projectArgGuidance = projectId === "default" ? " If this work belongs to another project, pass that project's id as `project` in BOTH calls instead \u2014 otherwise the gezel works in Default, with its workspace and memory." : "";
|
|
7868
8563
|
const nextHint = `
|
|
7869
8564
|
|
|
7870
|
-
NEXT: \`message_gezel({ gezel: "${res.gezelId}", message: "<one-line brief>"${projectArgFragment} })\` to start them, or \`
|
|
8565
|
+
NEXT: \`message_gezel({ gezel: "${res.gezelId}", message: "<one-line brief>"${projectArgFragment} })\` to start them, or \`assign_task({ ref, assignee: "${res.gezelId}" })\` to formally assign.${projectArgGuidance} Do NOT call \`ensure_gezel\` again with a similar \`jobTitle\` \u2014 it is idempotent and will keep returning the same gezel.`;
|
|
7871
8566
|
return {
|
|
7872
8567
|
content: [
|
|
7873
8568
|
{
|
|
@@ -7940,20 +8635,14 @@ server.tool(
|
|
|
7940
8635
|
server.tool(
|
|
7941
8636
|
"message_gezel",
|
|
7942
8637
|
'Send a message to another gezel (status check, nudge, broadcast, or file handoff). This is async fire-and-forget: it drops the message into their active project session and their reply surfaces automatically in a later turn. After a successful call, END YOUR TURN immediately \u2014 remaining alive can keep the recipient parked and occupies a provider slot. Use this for fan-out and ambient updates; emit every fan-out call in the same tool-call batch before ending. For explicit consultations where you need an inline answer before continuing, use `ask_gezel`. For substantial multi-step work, use tasks + `advance_task_step`. Do NOT just say \'I\'ll talk to Maya\' in chat; that does nothing. Call this tool. When the message asks them to produce a long-form file deliverable (a review, a report, an analysis, a written design), pass `expectedDeliverable: { kind: "file", filePath: "<path>" }` \u2014 the target will be steered to `write_file` the deliverable and reply with just the path + a short precis, instead of pasting the full text into chat (the matrix #2 squisq-review failure mode).',
|
|
7943
|
-
{
|
|
7944
|
-
gezel: z6.string().optional().describe("Target gezel id or display name"),
|
|
7945
|
-
// `gezelId` is the spelling models reach for; without it the slip
|
|
7946
|
-
// surfaces as a raw MCP -32602 Zod dump and costs a turn. Same
|
|
7947
|
-
// precedent as `ask_user_question`'s `prompt` / `description`.
|
|
7948
|
-
gezelId: z6.string().optional().describe("Alias for `gezel`."),
|
|
7949
|
-
message: z6.string().describe("What to ask or tell them"),
|
|
8638
|
+
MessageGezelInputSchema.extend({
|
|
7950
8639
|
project: z6.string().optional().describe(
|
|
7951
8640
|
"Project id or name. Defaults to YOUR current project, which is correct ONLY when the target should work in your project. If the work belongs to a project you spun up (via `start_project` / `fetch_repo`) and your own session is in a different project (typical for the Meester, who lives in `Default` and talks about other projects), you MUST pass `project` \u2014 otherwise the message lands in a sibling session where the target has none of the project's files, tasks, mission, or memory scope, and you'll get a \"what project are we talking about?\" reply. Pass the projectId returned by the macro that created the project; if you lost it, call `list_projects` first."
|
|
7952
8641
|
),
|
|
7953
8642
|
expectedDeliverable: ExpectedDeliverableArgSchema.optional().describe(
|
|
7954
8643
|
"Optional deliverable-shape hint. `{ kind: 'file', filePath: 'index.html' }`, `{ kind: 'file', filePath: 'review.md' }`, or `{ kind: 'file', filePath: 'logo.png' }` swaps the target's default chat-reply framing for a file-deliverable one. Text/source paths are written with `write_file`; image paths are rendered with `generate_image({ prompt, saveAs })`. Use this whenever the message asks for an actual workspace file; omit for normal short-message pings."
|
|
7955
8644
|
)
|
|
7956
|
-
},
|
|
8645
|
+
}).shape,
|
|
7957
8646
|
async ({ gezel, gezelId: gezelArg, message, project, expectedDeliverable }) => {
|
|
7958
8647
|
const target = gezel ?? gezelArg;
|
|
7959
8648
|
if (!target) {
|
|
@@ -8157,6 +8846,7 @@ var SPECIALIST_ROLES = z6.enum([
|
|
|
8157
8846
|
"researcher",
|
|
8158
8847
|
"developer",
|
|
8159
8848
|
"builder",
|
|
8849
|
+
"generalist",
|
|
8160
8850
|
"designer",
|
|
8161
8851
|
"writer",
|
|
8162
8852
|
"planner",
|
|
@@ -8175,6 +8865,7 @@ var ROLE_TO_JOB_TITLE = {
|
|
|
8175
8865
|
researcher: "Researcher",
|
|
8176
8866
|
developer: "Developer",
|
|
8177
8867
|
builder: "Builder",
|
|
8868
|
+
generalist: "Generalist",
|
|
8178
8869
|
designer: "Designer",
|
|
8179
8870
|
writer: "Copywriter",
|
|
8180
8871
|
planner: "Planner",
|
|
@@ -8191,7 +8882,7 @@ server.tool(
|
|
|
8191
8882
|
"Quick role-shaped consultation. Picks (or auto-creates) a gezel matching `role` and synchronously asks them `question` \u2014 their answer comes back as the tool result, ready to use inline within this turn. ONE call replaces the `ensure_gezel` \u2192 `ask_gezel` sequence. Use this for domain answers you need to keep working: 'researcher' for facts and prior art, 'designer' for visual / UX feedback, 'developer' or 'builder' for technical implementation calls, 'writer' for copy, 'planner' for breaking work down, 'reviewer' for QA on a draft, 'voorman' for project-status questions. Do NOT use this for shippable file or image deliverables (`index.html`, `review.md`, `logo.png`): first call `ensure_gezel`, then `message_gezel` with `expectedDeliverable: { kind: \"file\", filePath: \"<path>\" }` so the specialist works asynchronously and writes/renders the file. `ask_specialist` rejects file-shaped expectedDeliverable hints. The chosen specialist auto-joins your current project so the user can switch to their chat for follow-ups. For a specific known gezel use `ask_gezel`; for fan-out / fire-and-forget pings use `message_gezel`.",
|
|
8192
8883
|
{
|
|
8193
8884
|
role: SPECIALIST_ROLES.describe(
|
|
8194
|
-
"researcher = long-form analysis / facts / prior art (files a written report to disk by default), developer = team-oriented engineering, builder = solo product engineer, designer = visual/UX advice (does NOT render images), writer = copy/content, planner = strategy/decomposition, reviewer = QA/feedback (short structured verification reply by default), voorman = current-project lead, image-generator = render an actual PNG via generate_image (use this when you need a real image asset, not just visual feedback)."
|
|
8885
|
+
"researcher = long-form analysis / facts / prior art (files a written report to disk by default), developer = team-oriented engineering, builder = solo product engineer, generalist = one gezel for a whole multi-step task of any craft, designer = visual/UX advice (does NOT render images), writer = copy/content, planner = strategy/decomposition, reviewer = QA/feedback (short structured verification reply by default), voorman = current-project lead, image-generator = render an actual PNG via generate_image (use this when you need a real image asset, not just visual feedback)."
|
|
8195
8886
|
),
|
|
8196
8887
|
question: z6.string().min(1).describe(
|
|
8197
8888
|
"What you want them to answer. Be specific \u2014 they only see this question, not your prior conversation."
|
|
@@ -8519,29 +9210,7 @@ ${ask.text}`
|
|
|
8519
9210
|
server.tool(
|
|
8520
9211
|
"ask_user_question",
|
|
8521
9212
|
"Ask the user a question and end your turn. Call this whenever you'd otherwise stall waiting on the user \u2014 a design choice, a scope confirmation, an approval on something you drafted, a missing asset. The user sees a structured card in chat AND on the Home \"Needs your input\" panel AND as a count badge on the Home nav, so they WILL see it. Their answer arrives in your next turn as a new user message starting with `[Answer to: \u2026]`. When the answer is bounded (colors, yes/no, pick one of these three), always pass concrete `choices`; the user can still write a free-text note alongside unless `allowWriteIn: false`. For approvals where you've drafted a task or a document, attach `taskRef` (`projectId/num`) or `documentPath` so the user can review the artifact inline without leaving the card.",
|
|
8522
|
-
|
|
8523
|
-
question: z6.string().optional().describe("The question to pose to the user. Markdown ok."),
|
|
8524
|
-
// Common slip-ups some models reach for when they see an
|
|
8525
|
-
// "ask-a-question" tool — accept them so a naming mistake doesn't
|
|
8526
|
-
// surface as "technical error" to the user.
|
|
8527
|
-
prompt: z6.string().optional().describe(
|
|
8528
|
-
"Alias for `question`; when both are supplied, this explanatory text is preserved."
|
|
8529
|
-
),
|
|
8530
|
-
description: z6.string().optional().describe("Alias for `question`; distinct text is preserved below the question."),
|
|
8531
|
-
choices: coerceJsonArray(
|
|
8532
|
-
z6.array(z6.string()).max(20).optional().describe(
|
|
8533
|
-
'Preset answer choices. **Always pass these when the answer is bounded** (pick a color, pick yes/no, pick one of three options). Omit only for genuinely open-ended questions. Must be an actual JSON array `["a","b"]`, not a stringified array.'
|
|
8534
|
-
)
|
|
8535
|
-
),
|
|
8536
|
-
allowWriteIn: z6.boolean().optional().describe("Allow free-text alongside the choices. Default true."),
|
|
8537
|
-
multiSelect: z6.boolean().optional().describe("Let the user pick more than one choice. Default false."),
|
|
8538
|
-
taskRef: TaskRefSchema.optional().describe(
|
|
8539
|
-
'Approval-flow context: a task this question is about, in `projectId/num` form. The current task is attached automatically in task sessions; pass this only to override it. The UI renders the task header above the prompt with an "Open task" link.'
|
|
8540
|
-
),
|
|
8541
|
-
documentPath: z6.string().optional().describe(
|
|
8542
|
-
"Approval-flow context: a file this question is about. Accepts any of: a path under the global documents library; a path under the current project's `documents/` folder (pass just the relative path \u2014 the UI prepends the project prefix); or a path under the project's `artifacts/` folder. The server resolves in that order \u2014 you don't need to know which bucket the file lives in. The UI renders a collapsed preview + \"Open \u2026\" link with the kind chip matching what actually resolved."
|
|
8543
|
-
)
|
|
8544
|
-
},
|
|
9213
|
+
AskUserQuestionInputSchema.shape,
|
|
8545
9214
|
async ({
|
|
8546
9215
|
question,
|
|
8547
9216
|
prompt,
|
|
@@ -8620,7 +9289,7 @@ The runtime posted the card (id ${res.questionId}). The user sees it in chat, on
|
|
|
8620
9289
|
server.tool(
|
|
8621
9290
|
"list_projects",
|
|
8622
9291
|
"List every project. Projects are separate workspaces with their own file tree, artifacts, and chat history. The `default` project is the catch-all.",
|
|
8623
|
-
|
|
9292
|
+
EmptyInputSchema.shape,
|
|
8624
9293
|
async () => {
|
|
8625
9294
|
const res = await api.listProjects({ rollup: true });
|
|
8626
9295
|
const listing = res.projects.map(
|
|
@@ -8686,23 +9355,12 @@ function duplicateMacroProjectNotice(tool, existing) {
|
|
|
8686
9355
|
]
|
|
8687
9356
|
};
|
|
8688
9357
|
}
|
|
8689
|
-
var macroNameSchema =
|
|
8690
|
-
var macroAboutSchema =
|
|
8691
|
-
|
|
8692
|
-
|
|
8693
|
-
var
|
|
8694
|
-
|
|
8695
|
-
z6.string().optional()
|
|
8696
|
-
).describe(
|
|
8697
|
-
`Concrete success criteria as a bullet list. What does "done" look like? If you can't name it, you can't ship it.`
|
|
8698
|
-
);
|
|
8699
|
-
var macroTaskDescriptionSchema = z6.string().min(40).optional().describe(
|
|
8700
|
-
"Job-to-be-done for the kickoff task \u2014 what does success look like for the lead? Drives their first move. Distinct from `about` (overall scope) and `missionObjectives` (overall success)."
|
|
8701
|
-
);
|
|
8702
|
-
var macroTaskTitleSchema = z6.string().optional().describe('Title for the kickoff task. Defaults to "Build <name>".');
|
|
8703
|
-
var macroKickoffMessageSchema = z6.string().optional().describe(
|
|
8704
|
-
"Optional note from you to the lead \u2014 folded into the kickoff task description they read in their task-scoped session. Defaults to the mission-derived brief alone."
|
|
8705
|
-
);
|
|
9358
|
+
var macroNameSchema = StartProjectInputSchema.shape.name;
|
|
9359
|
+
var macroAboutSchema = StartProjectInputSchema.shape.about;
|
|
9360
|
+
var macroMissionSchema = StartProjectInputSchema.shape.missionObjectives;
|
|
9361
|
+
var macroTaskDescriptionSchema = StartProjectInputSchema.shape.taskDescription;
|
|
9362
|
+
var macroTaskTitleSchema = StartProjectInputSchema.shape.taskTitle;
|
|
9363
|
+
var macroKickoffMessageSchema = StartProjectInputSchema.shape.kickoffMessage;
|
|
8706
9364
|
function resolveMacroBrief(input) {
|
|
8707
9365
|
const about = usefulMacroText(input.about);
|
|
8708
9366
|
const mission = usefulMacroText(input.missionObjectives);
|
|
@@ -8749,6 +9407,7 @@ function normalizeSpecialistRole(value) {
|
|
|
8749
9407
|
)[1];
|
|
8750
9408
|
}
|
|
8751
9409
|
const resolved = resolveRoleId(lower) ?? resolveRoleId(normalized);
|
|
9410
|
+
if (resolved === "generalist") return "builder";
|
|
8752
9411
|
if (resolved && resolved !== "meester" && resolved !== "voorman") return resolved;
|
|
8753
9412
|
return "builder";
|
|
8754
9413
|
}
|
|
@@ -8859,6 +9518,9 @@ async function buildRetargetedBuildLoop(deliverablePath, briefText, opts = {}) {
|
|
|
8859
9518
|
|
|
8860
9519
|
**This deliverable is a raster image \u2014 render it with the image tool.** Call \`generate_image({ prompt, saveAs: "${deliverablePath}" })\` with a prompt faithful to the task brief. Do not call \`write_file\` for this path, encode image bytes as text/base64, install an image package, or substitute SVG/canvas code. The gate holds this step until a real image exists at \`${deliverablePath}\`.`;
|
|
8861
9520
|
}
|
|
9521
|
+
if (step.id === craftbook.entryStepId && step.toolPolicy) {
|
|
9522
|
+
step.toolPolicy = retargetEntryToolPolicy(policy, step.toolPolicy);
|
|
9523
|
+
}
|
|
8862
9524
|
if (step.advanceWhen) {
|
|
8863
9525
|
step.advanceWhen = { ...step.advanceWhen, file: deliverablePath, sniff };
|
|
8864
9526
|
}
|
|
@@ -9087,14 +9749,7 @@ ${idempotent.resultText}`
|
|
|
9087
9749
|
server.tool(
|
|
9088
9750
|
"start_project",
|
|
9089
9751
|
"Start a fresh project for any build request, from a single-file prototype to a multimodal product. Atomically: creates the project, selects an appropriate lead or crew for the effective execution mode, creates the kickoff task, and hands off its entry step. ONE call replaces the old multi-call setup ritual; preserve the requested deliverable paths and acceptance criteria in `taskDescription`.",
|
|
9090
|
-
|
|
9091
|
-
name: macroNameSchema,
|
|
9092
|
-
about: macroAboutSchema,
|
|
9093
|
-
missionObjectives: macroMissionSchema,
|
|
9094
|
-
taskDescription: macroTaskDescriptionSchema,
|
|
9095
|
-
taskTitle: macroTaskTitleSchema,
|
|
9096
|
-
kickoffMessage: macroKickoffMessageSchema
|
|
9097
|
-
},
|
|
9752
|
+
StartProjectInputSchema.shape,
|
|
9098
9753
|
async ({ name, about, missionObjectives, taskDescription, taskTitle, kickoffMessage }) => {
|
|
9099
9754
|
const brief = resolveMacroBrief({ name, about, missionObjectives, taskDescription });
|
|
9100
9755
|
const binaryRequest = binaryDocumentCraftbookRequest(brief);
|
|
@@ -9105,7 +9760,7 @@ server.tool(
|
|
|
9105
9760
|
"start_project"
|
|
9106
9761
|
);
|
|
9107
9762
|
}
|
|
9108
|
-
if (process.env.
|
|
9763
|
+
if (process.env.GEZEL_GENERALIST_KICKOFF === "on") {
|
|
9109
9764
|
return runFlatProject({ ...brief, taskTitle, kickoffMessage }, "start_project");
|
|
9110
9765
|
}
|
|
9111
9766
|
const repoRedirect = repoFetchRedirectForMacro({
|
|
@@ -9363,27 +10018,15 @@ server.tool(
|
|
|
9363
10018
|
server.tool(
|
|
9364
10019
|
"update_project",
|
|
9365
10020
|
'Update a project \u2014 rename, change description, set / clear its external working directory, assign a voorman gezel, set its lifecycle status, rewrite its about.md / missionObjectives.md, or set shared project properties (e.g. `content.language`, the designated language). Pass `workingDir: ""` to clear the external path. Pass `voormanGezelId: ""` to clear the voorman.',
|
|
9366
|
-
{
|
|
9367
|
-
id: z6.string().describe("Project id (from list_projects)"),
|
|
9368
|
-
name: z6.string().optional(),
|
|
9369
|
-
description: z6.string().optional(),
|
|
10021
|
+
UpdateProjectInputSchema.extend({
|
|
9370
10022
|
status: z6.enum(["active", "readonly", "inactive", "stable"]).optional().describe(
|
|
9371
10023
|
"Lifecycle status. `active`: normal. `stable`: finished/at rest \u2014 ambient check-in nudges pause until new task work resumes (the lifecycle also sets this automatically when the last active task closes, and clears it when a task is created/resumed). `readonly`/`inactive`: deliberate pauses."
|
|
9372
10024
|
),
|
|
9373
10025
|
workingDir: z6.string().optional().describe("Absolute path, or empty string to clear"),
|
|
9374
|
-
voormanGezelId: z6.string().optional().describe(
|
|
9375
|
-
"Gezel id that acts as voorman (foreman) of this project, or empty string to clear"
|
|
9376
|
-
),
|
|
9377
|
-
about: z6.string().optional().describe(
|
|
9378
|
-
"Replace the project's documents/about.md with this markdown. Flows into agent system prompts when a session is scoped to this project."
|
|
9379
|
-
),
|
|
9380
|
-
missionObjectives: z6.string().optional().describe(
|
|
9381
|
-
"Replace the project's documents/missionObjectives.md. Also flows into system prompts."
|
|
9382
|
-
),
|
|
9383
10026
|
properties: z6.record(z6.string(), z6.string()).optional().describe(
|
|
9384
10027
|
'Merge shared project configuration values (e.g. {"content.language": "Nederlands"}). Empty-string value deletes a key; unmentioned keys are untouched.'
|
|
9385
10028
|
)
|
|
9386
|
-
},
|
|
10029
|
+
}).shape,
|
|
9387
10030
|
async ({
|
|
9388
10031
|
id,
|
|
9389
10032
|
name,
|
|
@@ -9416,9 +10059,7 @@ server.tool(
|
|
|
9416
10059
|
server.tool(
|
|
9417
10060
|
"list_project_gezels",
|
|
9418
10061
|
"List every gezel available in a project, in two clearly labeled sections: the shared roster pulled into this project and workspace-local gezels such as `@project` derived from AGENTS.md/CLAUDE.md or `.gezel/`. Use this single call to answer 'who is on this project?' or discover a project-local specialist.",
|
|
9419
|
-
|
|
9420
|
-
project: z6.string().optional().describe("Project id or name \u2014 defaults to your current project")
|
|
9421
|
-
},
|
|
10062
|
+
ListProjectGezelsInputSchema.shape,
|
|
9422
10063
|
async ({ project }) => {
|
|
9423
10064
|
const resolvedProject = project ? await resolveProjectId(project) : projectId;
|
|
9424
10065
|
const [roster, local, allGezels] = await Promise.all([
|
|
@@ -9470,10 +10111,7 @@ server.tool(
|
|
|
9470
10111
|
server.tool(
|
|
9471
10112
|
"add_gezel_to_project",
|
|
9472
10113
|
"Add a gezel to a project's roster explicitly. Most paths auto-add (voorman assignment, opening a session, message_gezel/ask_gezel, task assignment), so reach for this only when you want to pre-populate the team without one of those triggers \u2014 e.g. introducing a reviewer who hasn't been pinged yet. Idempotent.",
|
|
9473
|
-
|
|
9474
|
-
gezel: z6.string().describe("Gezel id or display name"),
|
|
9475
|
-
project: z6.string().optional().describe("Project id or name \u2014 defaults to your current project")
|
|
9476
|
-
},
|
|
10114
|
+
AddGezelToProjectInputSchema.shape,
|
|
9477
10115
|
async ({ gezel, project }) => {
|
|
9478
10116
|
const resolvedProject = project ? await resolveProjectId(project) : projectId;
|
|
9479
10117
|
const resolvedGezel = await resolveGezelId(gezel);
|
|
@@ -9640,11 +10278,7 @@ function setStepDeliverableCall(ref, stepId, deliverable) {
|
|
|
9640
10278
|
server.tool(
|
|
9641
10279
|
"list_tasks",
|
|
9642
10280
|
"List tasks. Optionally filter by project, status, or assignee gezel id. Sorted newest-updated first.",
|
|
9643
|
-
|
|
9644
|
-
project: z6.string().optional(),
|
|
9645
|
-
status: z6.enum(["draft", "paused", "active", "complete", "canceled"]).optional(),
|
|
9646
|
-
assignee: z6.string().optional().describe("gezel id")
|
|
9647
|
-
},
|
|
10281
|
+
ListTasksInputSchema.shape,
|
|
9648
10282
|
async ({ project, status, assignee }) => {
|
|
9649
10283
|
const projectId2 = project ? await resolveProjectId(project) : void 0;
|
|
9650
10284
|
const res = projectId2 ? await api.listProjectTasks(
|
|
@@ -9667,7 +10301,7 @@ ${res.tasks.map(formatTaskLine).join("\n")}` : summary
|
|
|
9667
10301
|
server.tool(
|
|
9668
10302
|
"get_task",
|
|
9669
10303
|
"Get one task by ref (format: `projectId/num`). Returns full detail: status, assignee, every phase, active phase, any cron schedule, parent task.",
|
|
9670
|
-
|
|
10304
|
+
GetTaskInputSchema.shape,
|
|
9671
10305
|
async ({ ref }) => {
|
|
9672
10306
|
const parsed = await parseRef(ref);
|
|
9673
10307
|
const t = await api.getTask(parsed.projectId, parsed.num);
|
|
@@ -9688,15 +10322,7 @@ ${JSON.stringify(t, null, 2)}` }
|
|
|
9688
10322
|
var cronOverlapEnum = z6.enum(["skip", "queue", "concurrent"]).describe(
|
|
9689
10323
|
"Overlap policy when a cron fires while a prior child is still active. 'skip' (default) doesn't spawn if any active child exists; 'queue' always spawns and lets the runner throttle; 'concurrent' spawns unconditionally."
|
|
9690
10324
|
);
|
|
9691
|
-
var stepBlueprintSchema =
|
|
9692
|
-
name: z6.string().min(1),
|
|
9693
|
-
description: z6.string().optional(),
|
|
9694
|
-
prompt: z6.string().optional(),
|
|
9695
|
-
suggestedGezelId: z6.string().optional(),
|
|
9696
|
-
suggestedRole: z6.string().optional().describe('Role hint ("developer", "reviewer") resolved to a gezel at step activation.'),
|
|
9697
|
-
deliverable: deliverableArg,
|
|
9698
|
-
terminal: z6.boolean().optional().describe("Final step \u2014 completing it completes the task.")
|
|
9699
|
-
});
|
|
10325
|
+
var stepBlueprintSchema = StepBlueprintSchema.extend({ deliverable: deliverableArg });
|
|
9700
10326
|
function blueprintToStep(s) {
|
|
9701
10327
|
const d = coerceBlueprintDeliverable(s.deliverable);
|
|
9702
10328
|
return {
|
|
@@ -9729,15 +10355,7 @@ var fanoutArg = coerceJsonObject(
|
|
|
9729
10355
|
server.tool(
|
|
9730
10356
|
"create_task",
|
|
9731
10357
|
'Create a task in a project. Always starts with status "active" at the first step of its craftbook. Provide either `craftbookId` (a recipe from the catalog) OR inline `steps` (an ad-hoc craftbook embedded in the task). For recurring work, also pass `spawnsCraftbookId` or `spawnsSteps` plus a `cron` expression; for N parallel copies, pass spawn-side steps plus a `fanout` config.',
|
|
9732
|
-
{
|
|
9733
|
-
project: z6.string().describe("Project id"),
|
|
9734
|
-
title: z6.string().min(1),
|
|
9735
|
-
description: z6.string().min(40).describe(
|
|
9736
|
-
`The job-to-be-done. State the problem from the user's perspective \u2014 what does success look like? Bad: "set up the website". Good: "Eliza wants an online shop for her pet care services so walk-in customers can book appointments online; success means a working checkout flow by end of month." The voorman landing on this task later reads this and needs to actually know what they're solving.`
|
|
9737
|
-
),
|
|
9738
|
-
plan: z6.string().optional().describe(
|
|
9739
|
-
"The voorman's approach. Usually omitted at creation and filled in later via update_task once the work has been scoped. Distinct from per-step notes (the progress log) \u2014 this is the plan."
|
|
9740
|
-
),
|
|
10358
|
+
CreateTaskInputSchema.extend({
|
|
9741
10359
|
assignee: assigneeArg().optional().describe(
|
|
9742
10360
|
`${ASSIGNEE_ARG_DESCRIPTION} Naming someone here just pins an owner the per-step roles override anyway.`
|
|
9743
10361
|
),
|
|
@@ -9765,7 +10383,7 @@ server.tool(
|
|
|
9765
10383
|
dispatch: z6.boolean().optional().describe(
|
|
9766
10384
|
"Hand the entry step to its assignee immediately as a task-scoped handoff (single-channel kickoff). Invalid on drafts and cron/fanout hosts."
|
|
9767
10385
|
)
|
|
9768
|
-
},
|
|
10386
|
+
}).shape,
|
|
9769
10387
|
async ({
|
|
9770
10388
|
project,
|
|
9771
10389
|
title,
|
|
@@ -10395,13 +11013,7 @@ The task's steps are: ${roster}.`;
|
|
|
10395
11013
|
server.tool(
|
|
10396
11014
|
"advance_task_step",
|
|
10397
11015
|
"Mark the named step complete and activate the next one (or a specifically-named step). THIS is how you hand off to another gezel \u2014 calling this tool automatically opens a fresh session with the new step's assignee (or `suggestedGezelId`) and kicks them off on the work. Do NOT just say \"ready to hand off\" in chat; that does nothing. Call this tool. A SUCCESSFUL call is terminal for this gezel's turn: stop immediately and yield; the successor owns all further work. A rejected gate is not terminal \u2014 repair the named issue and retry.",
|
|
10398
|
-
|
|
10399
|
-
ref: z6.string(),
|
|
10400
|
-
stepId: z6.string().describe("Id of the step to complete"),
|
|
10401
|
-
next: z6.string().optional().describe(
|
|
10402
|
-
'Id of the step to activate next, or "next" / omit to advance to the following step in order.'
|
|
10403
|
-
)
|
|
10404
|
-
},
|
|
11016
|
+
AdvanceTaskStepInputSchema.shape,
|
|
10405
11017
|
async ({ ref, stepId, next }) => {
|
|
10406
11018
|
const draftBlock = partialEdits.blockReason("advance_task_step");
|
|
10407
11019
|
if (draftBlock) return errorResult(draftBlock);
|
|
@@ -10446,8 +11058,21 @@ ${pausedNote}`,
|
|
|
10446
11058
|
sessionStepCompleted = true;
|
|
10447
11059
|
const active = task.craftbook.steps.find((s) => s.id === task.activeStepId);
|
|
10448
11060
|
const assigneeId = active?.assignee?.kind === "gezel" ? active.assignee.gezelId : active?.suggestedGezelId;
|
|
10449
|
-
const handoffNote = advanceHandoffNote({
|
|
10450
|
-
|
|
11061
|
+
const handoffNote = advanceHandoffNote({
|
|
11062
|
+
status: task.status,
|
|
11063
|
+
assigneeId,
|
|
11064
|
+
ownerStep: isOwnerStep(active)
|
|
11065
|
+
});
|
|
11066
|
+
const statusLine = advanceStatusLine({
|
|
11067
|
+
completedName: task.craftbook.steps.find((s) => s.id === stepId)?.name ?? stepId,
|
|
11068
|
+
nextName: active?.name,
|
|
11069
|
+
status: task.status,
|
|
11070
|
+
taskTitle: task.title,
|
|
11071
|
+
ownerStep: isOwnerStep(active)
|
|
11072
|
+
});
|
|
11073
|
+
const text = `${statusLine}
|
|
11074
|
+
|
|
11075
|
+
Completed step "${stepId}" on ${ref}. Active step is now "${active?.name ?? task.activeStepId ?? "(none)"}".${handoffNote}`;
|
|
10451
11076
|
return okResult(
|
|
10452
11077
|
TaskToolOutputSchema,
|
|
10453
11078
|
{
|
|
@@ -10465,10 +11090,7 @@ ${pausedNote}`,
|
|
|
10465
11090
|
server.tool(
|
|
10466
11091
|
"read_task_notes",
|
|
10467
11092
|
"Read the chronological feed of timestamped notes for a task (or a specific step). Omit stepId to read the whole task feed across every step. Each entry has an author (a gezel or the user) and was appended at a known time \u2014 newest first.",
|
|
10468
|
-
|
|
10469
|
-
ref: z6.string(),
|
|
10470
|
-
stepId: z6.string().optional()
|
|
10471
|
-
},
|
|
11093
|
+
ReadTaskNotesInputSchema.shape,
|
|
10472
11094
|
async ({ ref, stepId }) => {
|
|
10473
11095
|
const parsed = await parseRef(ref);
|
|
10474
11096
|
const effectiveStep = stepId?.trim() || void 0;
|
|
@@ -10492,23 +11114,7 @@ ${JSON.stringify({ notes })}` }
|
|
|
10492
11114
|
server.tool(
|
|
10493
11115
|
"write_task_note",
|
|
10494
11116
|
"Append one focused, dated, attributed note to a task. Prefer many small notes over a long blob \u2014 teammates and you will read this feed later. Author is auto-attributed to you.",
|
|
10495
|
-
|
|
10496
|
-
ref: z6.string(),
|
|
10497
|
-
text: z6.string().min(1).optional().describe("The note body. Markdown ok. Required unless you pass `note` / `content` instead."),
|
|
10498
|
-
// `note` and `content` are the two names models reach for on a tool
|
|
10499
|
-
// called `write_task_note`. `write_task_note` is the single most common
|
|
10500
|
-
// argument-validation failure in the whole eval corpus, and `content` is
|
|
10501
|
-
// not even a guess — the shipped `investigate` and `pull-request-review`
|
|
10502
|
-
// craftbooks instruct the assignee to call
|
|
10503
|
-
// `write_task_note({ ref, content: … })`, so following the catalog
|
|
10504
|
-
// verbatim earns a -32602. The rejection happens in the SDK's schema
|
|
10505
|
-
// validation before the handler runs, so no coercion layer downstream can
|
|
10506
|
-
// rescue it: the model burns a turn re-reading the schema. Same precedent
|
|
10507
|
-
// as `ask_user_question`'s `prompt` / `description` aliases.
|
|
10508
|
-
note: z6.string().min(1).optional().describe("Alias for `text`."),
|
|
10509
|
-
content: z6.string().min(1).optional().describe("Alias for `text`."),
|
|
10510
|
-
stepId: z6.string().optional()
|
|
10511
|
-
},
|
|
11117
|
+
WriteTaskNoteInputSchema.shape,
|
|
10512
11118
|
async ({ ref, text, note, content, stepId }) => {
|
|
10513
11119
|
const body = text ?? note ?? content;
|
|
10514
11120
|
if (!body) {
|
|
@@ -10542,6 +11148,94 @@ server.tool(
|
|
|
10542
11148
|
);
|
|
10543
11149
|
}
|
|
10544
11150
|
);
|
|
11151
|
+
server.tool(
|
|
11152
|
+
"manage_task",
|
|
11153
|
+
'Pause, resume, or cancel a task when the user asks \u2014 "pause the deck", "try the PowerPoint again", "cancel that". `resume` also restarts a task that paused for help, with fresh budgets, and works only when the user asked for it this turn. Finishing a task is not an action here: its assignee does that through the step gates.',
|
|
11154
|
+
ManageTaskInputSchema.shape,
|
|
11155
|
+
async ({ ref, action, reason }) => {
|
|
11156
|
+
const bare = ref.trim().replace(/^#/, "");
|
|
11157
|
+
const parsed = await parseRef(
|
|
11158
|
+
/^\d+$/.test(bare) && !sessionTaskRef ? `${projectId}/${bare}` : ref
|
|
11159
|
+
);
|
|
11160
|
+
const current = await api.getTask(parsed.projectId, parsed.num);
|
|
11161
|
+
const taskRef = current.ref;
|
|
11162
|
+
const why = reason?.trim();
|
|
11163
|
+
const leaveNote = async (heading) => {
|
|
11164
|
+
if (!why) return;
|
|
11165
|
+
await api.appendTaskNote(
|
|
11166
|
+
parsed.projectId,
|
|
11167
|
+
parsed.num,
|
|
11168
|
+
{ text: normalizeMarkdown(`### ${heading}
|
|
11169
|
+
|
|
11170
|
+
${why}`) },
|
|
11171
|
+
gezelId ? { actorGezelId: gezelId } : {}
|
|
11172
|
+
).catch(() => {
|
|
11173
|
+
});
|
|
11174
|
+
};
|
|
11175
|
+
const done = (summary, task = current) => okResult(
|
|
11176
|
+
TaskToolOutputSchema,
|
|
11177
|
+
{ summary, operation: `manage_${action}`, ref: taskRef, status: task.status, task },
|
|
11178
|
+
{ text: summary }
|
|
11179
|
+
);
|
|
11180
|
+
const settled = current.status === "complete" || current.status === "canceled";
|
|
11181
|
+
if (action === "pause") {
|
|
11182
|
+
if (current.status !== "active") {
|
|
11183
|
+
return done(`${taskRef} is ${current.status}, not running \u2014 nothing to pause.`);
|
|
11184
|
+
}
|
|
11185
|
+
const updated = await api.setTaskStatus(parsed.projectId, parsed.num, "paused");
|
|
11186
|
+
await leaveNote("Paused");
|
|
11187
|
+
return done(`Paused ${taskRef}.`, updated);
|
|
11188
|
+
}
|
|
11189
|
+
if (action === "cancel") {
|
|
11190
|
+
if (settled) return done(`${taskRef} is already ${current.status}.`);
|
|
11191
|
+
let updated;
|
|
11192
|
+
try {
|
|
11193
|
+
updated = await api.setTaskStatus(parsed.projectId, parsed.num, "canceled");
|
|
11194
|
+
} catch (err) {
|
|
11195
|
+
if (/\b403\b/.test(err instanceof Error ? err.message : String(err))) {
|
|
11196
|
+
return errorResult(
|
|
11197
|
+
`Only the user can cancel ${taskRef}, and canceling cannot be undone. Ask them first \u2014 "should I cancel it?" \u2014 and cancel it when they say so. Pause it instead if it needs to stop now.`,
|
|
11198
|
+
{ code: "needs_user", retryable: false }
|
|
11199
|
+
);
|
|
11200
|
+
}
|
|
11201
|
+
throw err;
|
|
11202
|
+
}
|
|
11203
|
+
await leaveNote("Canceled");
|
|
11204
|
+
return done(`Canceled ${taskRef}.`, updated);
|
|
11205
|
+
}
|
|
11206
|
+
if (current.status === "active") return done(`${taskRef} is already running.`);
|
|
11207
|
+
if (current.status === "draft") {
|
|
11208
|
+
return errorResult(
|
|
11209
|
+
`${taskRef} is a draft plan that has not started. The user starts it from the plan's card.`,
|
|
11210
|
+
{ retryable: false }
|
|
11211
|
+
);
|
|
11212
|
+
}
|
|
11213
|
+
if (settled) {
|
|
11214
|
+
return errorResult(
|
|
11215
|
+
`${taskRef} is ${current.status} and cannot be resumed. If the user wants another run, start a fresh one (for a craftbook, invoke_craftbook).`,
|
|
11216
|
+
{ retryable: false }
|
|
11217
|
+
);
|
|
11218
|
+
}
|
|
11219
|
+
let result;
|
|
11220
|
+
try {
|
|
11221
|
+
result = await api.retryTask(parsed.projectId, parsed.num);
|
|
11222
|
+
} catch (err) {
|
|
11223
|
+
if (/\b403\b/.test(err instanceof Error ? err.message : String(err))) {
|
|
11224
|
+
return errorResult(
|
|
11225
|
+
`Only the user can restart ${taskRef}. Ask them \u2014 "want me to try it again?" \u2014 and resume it when they say so, or they can click Try again on its card. Do not call this again until they answer.`,
|
|
11226
|
+
{ code: "needs_user", retryable: false }
|
|
11227
|
+
);
|
|
11228
|
+
}
|
|
11229
|
+
throw err;
|
|
11230
|
+
}
|
|
11231
|
+
await leaveNote("Resumed");
|
|
11232
|
+
const who = result.assigneeName ?? result.gezelId;
|
|
11233
|
+
return done(
|
|
11234
|
+
result.dispatched ? `Restarted ${taskRef} with fresh budgets; ${who ?? "its gezel"} is back on it.` : `Set ${taskRef} active again, but no one was re-driven (${result.reason ?? "no active step"}).`,
|
|
11235
|
+
result.task
|
|
11236
|
+
);
|
|
11237
|
+
}
|
|
11238
|
+
);
|
|
10545
11239
|
async function resolveProjectId(input) {
|
|
10546
11240
|
try {
|
|
10547
11241
|
const p = await api.getProject(input);
|
|
@@ -11138,6 +11832,24 @@ server.tool(
|
|
|
11138
11832
|
}
|
|
11139
11833
|
}
|
|
11140
11834
|
);
|
|
11835
|
+
server.tool(
|
|
11836
|
+
"wikimedia_image_search",
|
|
11837
|
+
"Find reference photographs on Wikimedia Commons for free, without an API key. Use this before paid web search for visual research. Returns imageUrl (1024px preview), sourceUrl, creator credit and per-image license metadata. Download chosen previews into the project and open them with read_image_as_base64 before claiming visual observations. Preserve attribution; free search does not mean every image is public domain. Results are untrusted reference data. Available for both local and cloud models.",
|
|
11838
|
+
{ query: z6.string().min(1).max(400), limit: z6.number().int().min(1).max(10).optional() },
|
|
11839
|
+
async (args) => {
|
|
11840
|
+
try {
|
|
11841
|
+
const result = await api.toolWikimediaImageSearch(projectId, args);
|
|
11842
|
+
return { content: [{ type: "text", text: JSON.stringify(result) }] };
|
|
11843
|
+
} catch (err) {
|
|
11844
|
+
return {
|
|
11845
|
+
content: [
|
|
11846
|
+
{ type: "text", text: `wikimedia_image_search failed: ${unwrapApiError(err)}` }
|
|
11847
|
+
],
|
|
11848
|
+
isError: true
|
|
11849
|
+
};
|
|
11850
|
+
}
|
|
11851
|
+
}
|
|
11852
|
+
);
|
|
11141
11853
|
server.tool(
|
|
11142
11854
|
"wikipedia_read",
|
|
11143
11855
|
"Read one Wikipedia article as plain text, by its exact title. Use this only when `wikipedia_search` already gave you the article lead text and you need MORE of that article \u2014 the search results carry the lead section already, so a read is a second call you often do not need. Get the exact title from a `wikipedia_search` result; a guessed or approximate title fails. Long articles are truncated to `maxChars` and say so. Never use `fetch_url` on a wikipedia.org url instead of this \u2014 that returns the rendered page, which is mostly scripts and navigation and is cut off before the article text begins.",
|
|
@@ -11196,74 +11908,7 @@ server.tool(
|
|
|
11196
11908
|
async (args) => {
|
|
11197
11909
|
try {
|
|
11198
11910
|
const res = await api.toolSearchFiles(projectId, args);
|
|
11199
|
-
|
|
11200
|
-
Results truncated (${res.truncationReason ?? "limit"}).${res.nextCursor !== void 0 ? ` Continue with cursor=${res.nextCursor}, or narrow path/includeGlobs/pattern.` : " Narrow path/includeGlobs/pattern."}` : "";
|
|
11201
|
-
if (res.mode === "count") {
|
|
11202
|
-
const qualifier = res.truncated ? "at least " : "";
|
|
11203
|
-
const summary = `${qualifier}${res.count} matching line${res.count === 1 ? "" : "s"} (engine=${res.engine}).`;
|
|
11204
|
-
return okResult(
|
|
11205
|
-
SearchToolOutputSchema,
|
|
11206
|
-
{
|
|
11207
|
-
summary,
|
|
11208
|
-
query: args.pattern,
|
|
11209
|
-
matches: [],
|
|
11210
|
-
count: res.count,
|
|
11211
|
-
truncated: res.truncated,
|
|
11212
|
-
engine: res.engine,
|
|
11213
|
-
mode: res.mode,
|
|
11214
|
-
...res.nextCursor !== void 0 ? { nextCursor: res.nextCursor } : {},
|
|
11215
|
-
...res.truncationReason ? { truncationReason: res.truncationReason } : {}
|
|
11216
|
-
},
|
|
11217
|
-
{ text: `${summary}${truncation}` }
|
|
11218
|
-
);
|
|
11219
|
-
}
|
|
11220
|
-
if (res.mode === "files") {
|
|
11221
|
-
const header2 = `${res.files.length} matching file${res.files.length === 1 ? "" : "s"} (engine=${res.engine})`;
|
|
11222
|
-
return okResult(
|
|
11223
|
-
SearchToolOutputSchema,
|
|
11224
|
-
{
|
|
11225
|
-
summary: `${header2}.`,
|
|
11226
|
-
query: args.pattern,
|
|
11227
|
-
matches: res.files.map((path) => ({ path })),
|
|
11228
|
-
count: res.files.length,
|
|
11229
|
-
truncated: res.truncated,
|
|
11230
|
-
engine: res.engine,
|
|
11231
|
-
mode: res.mode,
|
|
11232
|
-
...res.nextCursor !== void 0 ? { nextCursor: res.nextCursor } : {},
|
|
11233
|
-
...res.truncationReason ? { truncationReason: res.truncationReason } : {}
|
|
11234
|
-
},
|
|
11235
|
-
{ text: `${header2}
|
|
11236
|
-
${res.files.join("\n") || "(none)"}${truncation}` }
|
|
11237
|
-
);
|
|
11238
|
-
}
|
|
11239
|
-
const lines = res.matches.flatMap((match, index) => {
|
|
11240
|
-
const block = [
|
|
11241
|
-
...(match.before ?? []).map((line) => `${match.path}-${line.line}-${line.text}`),
|
|
11242
|
-
`${match.path}:${match.line}:${match.text}`,
|
|
11243
|
-
...(match.after ?? []).map((line) => `${match.path}-${line.line}-${line.text}`)
|
|
11244
|
-
];
|
|
11245
|
-
if (index < res.matches.length - 1 && (match.before?.length || match.after?.length)) {
|
|
11246
|
-
block.push("--");
|
|
11247
|
-
}
|
|
11248
|
-
return block;
|
|
11249
|
-
});
|
|
11250
|
-
const header = `${res.matches.length} match${res.matches.length === 1 ? "" : "es"} (engine=${res.engine})`;
|
|
11251
|
-
return okResult(
|
|
11252
|
-
SearchToolOutputSchema,
|
|
11253
|
-
{
|
|
11254
|
-
summary: `${header}.`,
|
|
11255
|
-
query: args.pattern,
|
|
11256
|
-
matches: res.matches,
|
|
11257
|
-
count: res.matches.length,
|
|
11258
|
-
truncated: res.truncated,
|
|
11259
|
-
engine: res.engine,
|
|
11260
|
-
mode: res.mode,
|
|
11261
|
-
...res.nextCursor !== void 0 ? { nextCursor: res.nextCursor } : {},
|
|
11262
|
-
...res.truncationReason ? { truncationReason: res.truncationReason } : {}
|
|
11263
|
-
},
|
|
11264
|
-
{ text: `${header}
|
|
11265
|
-
${lines.join("\n") || "(no matches)"}${truncation}` }
|
|
11266
|
-
);
|
|
11911
|
+
return workspaceGrepResult(args, res);
|
|
11267
11912
|
} catch (err) {
|
|
11268
11913
|
const msg = unwrapApiError(err);
|
|
11269
11914
|
return errorResult(`grep_files failed: ${msg}`);
|
|
@@ -11597,8 +12242,7 @@ function searchTextBudgetTokens() {
|
|
|
11597
12242
|
server.tool(
|
|
11598
12243
|
"search",
|
|
11599
12244
|
"Search indexed knowledge by meaning and keywords through one simple surface. Covers the active and linked projects' workspaces, artifacts, and memories, the shared document library, and any installed knowledge catalogs (reference material with citation URIs). Every result carries provenance and an exact path/line when available \u2014 open hits with `read_file` (workspace, including `../<project-id>/...` linked paths), `read_artifact` (artifacts), or `read_document` (shared paths and knowledge:// URIs). This is the preferred discovery tool; `grep_files` remains best for exact strings and regular expressions.",
|
|
11600
|
-
{
|
|
11601
|
-
query: z6.string().min(1).describe("Natural-language description or keywords."),
|
|
12245
|
+
SearchInputSchema.extend({
|
|
11602
12246
|
sources: z6.array(
|
|
11603
12247
|
z6.enum(["workspace", "artifacts", "project-memory", "gezel-memory", "shared", "knowledge"])
|
|
11604
12248
|
).optional().describe("Optional corpus filter. Omit to search all knowledge available to this project."),
|
|
@@ -11609,7 +12253,7 @@ server.tool(
|
|
|
11609
12253
|
pathPrefix: z6.string().min(1).optional().describe(
|
|
11610
12254
|
'Only results under this path prefix (e.g. "src/engine/" or "../<project-id>/docs/"). Narrowing only.'
|
|
11611
12255
|
)
|
|
11612
|
-
},
|
|
12256
|
+
}).shape,
|
|
11613
12257
|
async ({ query, sources, maxResults, cursor, pathPrefix }) => {
|
|
11614
12258
|
try {
|
|
11615
12259
|
const res = await api.toolSearch(projectId, {
|
|
@@ -11644,7 +12288,10 @@ server.tool(
|
|
|
11644
12288
|
return `[craftbook:${source}] ${craftbook.name} (${craftbook.id})${description}
|
|
11645
12289
|
If this procedure fits and \`invoke_craftbook\` is available, call \`invoke_craftbook\` directly with arguments \`${callArguments}\`; otherwise ignore it.`;
|
|
11646
12290
|
});
|
|
11647
|
-
const
|
|
12291
|
+
const incomplete = res.sourcesIncomplete === true;
|
|
12292
|
+
const weak = res.hiddenBelowRelevanceFloor ?? 0;
|
|
12293
|
+
const weakNote = weak > 0 ? ` (${weak} weak match${weak === 1 ? "" : "es"} hidden)` : "";
|
|
12294
|
+
const resultSummary = modelResults.length ? `Found ${modelResults.length} relevant result${modelResults.length === 1 ? "" : "s"} across active, linked, and shared project knowledge${incomplete ? " (partial: some sources did not answer in time)" : res.truncated ? " (truncated)" : ""}${weakNote}` : incomplete ? "Nothing returned yet: some sources did not answer in time, so this is not evidence the topic is absent. Repeat the same search once before concluding there is no indexed material" : weak > 0 ? `No closely relevant results${weakNote}` : "No indexed project knowledge matched";
|
|
11648
12295
|
const summary = res.craftbooks.length ? `${resultSummary}; suggested ${res.craftbooks.length} relevant craftbook${res.craftbooks.length === 1 ? "" : "s"}.` : `${resultSummary}.`;
|
|
11649
12296
|
const craftbookSection = craftbookLines.length ? `Craftbook options:
|
|
11650
12297
|
${craftbookLines.join("\n")}` : null;
|
|
@@ -11675,7 +12322,7 @@ ${craftbookLines.join("\n")}` : null;
|
|
|
11675
12322
|
count: modelResults.length,
|
|
11676
12323
|
truncated: moreExists,
|
|
11677
12324
|
...nextCursor !== void 0 ? { nextCursor } : {},
|
|
11678
|
-
...hidden > 0 ? { truncationReason: "output" } : res.truncated ? { truncationReason: "limit" } : {},
|
|
12325
|
+
...hidden > 0 ? { truncationReason: "output" } : incomplete ? { truncationReason: "incomplete" } : res.truncated ? { truncationReason: "limit" } : {},
|
|
11679
12326
|
engine: "scoped-index",
|
|
11680
12327
|
craftbooks: res.craftbooks
|
|
11681
12328
|
},
|
|
@@ -12190,9 +12837,10 @@ ${lines.join("\n") || "(no matches)"}` }
|
|
|
12190
12837
|
);
|
|
12191
12838
|
server.tool(
|
|
12192
12839
|
"read_doc_as_markdown",
|
|
12193
|
-
"Read an office document (Word/PDF/PowerPoint/Excel) as scannable markdown. gezel converts the binary document on demand and returns its markdown \u2014 use this instead of trying to read_file a binary doc. Pass the document path (e.g. notes/spec.docx).",
|
|
12840
|
+
"Read an office document (Word/PDF/PowerPoint/Excel) as scannable markdown. gezel converts the binary document on demand and returns its markdown \u2014 use this instead of trying to read_file a binary doc. Pass the document path (e.g. notes/spec.docx); set `artifact: true` for a document in the artifacts drawer.",
|
|
12194
12841
|
{
|
|
12195
|
-
path: z6.string().min(1).describe("
|
|
12842
|
+
path: z6.string().min(1).describe("Path to the document, relative to the workspace (or to the artifacts drawer)."),
|
|
12843
|
+
artifact: z6.boolean().optional().describe("True when the document is in the artifacts drawer rather than the workspace.")
|
|
12196
12844
|
},
|
|
12197
12845
|
async (args) => {
|
|
12198
12846
|
try {
|
|
@@ -12485,9 +13133,7 @@ ${res.stderr}` : ""}`;
|
|
|
12485
13133
|
server.tool(
|
|
12486
13134
|
"list_scripts",
|
|
12487
13135
|
'List the scripts available to this gezel: project-scoped scripts plus the read-only STANDARD library packed into the app. Each entry returns its name, one-line description, input fields (with types), and required capabilities. Standard-library entries (mostly `kind: gate` checks like checkFileMinBytes / checkContains / checkHtmlComplete) are the preferred vocabulary for craftbook step gates \u2014 reference them with `scope: "standard"` and parameterize via `inputs` instead of writing new scripts.',
|
|
12488
|
-
|
|
12489
|
-
project: z6.string().optional().describe("Project id or name. Defaults to the current project.")
|
|
12490
|
-
},
|
|
13136
|
+
ListScriptsInputSchema.shape,
|
|
12491
13137
|
async ({ project }) => {
|
|
12492
13138
|
const resolved = project ? await resolveProjectId(project) : projectId;
|
|
12493
13139
|
const res = await api.listProjectScripts(resolved);
|
|
@@ -12526,12 +13172,8 @@ ${sections.join("\n\n")}` }
|
|
|
12526
13172
|
server.tool(
|
|
12527
13173
|
"run_installed_script",
|
|
12528
13174
|
"Run an ALREADY-INSTALLED project script by NAME \u2014 one of the scripts `list_scripts` shows, including ops/probe scripts a craftbook installed. Takes a name, never a file path. To run a file you just wrote yourself (e.g. `tools/derive.mjs`), use `run_nodejs_script` \u2014 not this. When a task, kickoff, or step tells you to run a named script, THIS is the runner \u2014 not `run_package_script` or `run_npx`. Input is validated against the script's meta.inputs. Returns the stamped output, per-call trace summary, and run id. Runs with undeclared capabilities or missing required inputs fail fast.",
|
|
12529
|
-
|
|
12530
|
-
|
|
12531
|
-
name: z6.string().describe("Script name (matches meta.name and the .ts filename)."),
|
|
12532
|
-
input: z6.record(z6.string(), z6.unknown()).optional()
|
|
12533
|
-
},
|
|
12534
|
-
async ({ project, name, input }) => {
|
|
13175
|
+
RunInstalledScriptInputSchema.shape,
|
|
13176
|
+
async ({ project, name, scope, input }) => {
|
|
12535
13177
|
const looksLikePath = /[/\\]/.test(name) || /\.(mjs|cjs|js|ts|py|sh)$/i.test(name);
|
|
12536
13178
|
if (looksLikePath) {
|
|
12537
13179
|
return {
|
|
@@ -12548,6 +13190,7 @@ server.tool(
|
|
|
12548
13190
|
try {
|
|
12549
13191
|
const res = await api.runProjectScript(resolved, {
|
|
12550
13192
|
name,
|
|
13193
|
+
...scope ? { scope } : {},
|
|
12551
13194
|
...input ? { input } : {}
|
|
12552
13195
|
});
|
|
12553
13196
|
return formatScriptRunResult(res);
|
|
@@ -12560,10 +13203,7 @@ server.tool(
|
|
|
12560
13203
|
server.tool(
|
|
12561
13204
|
"get_script_run",
|
|
12562
13205
|
"Fetch a persisted ScriptRun by id. Returns the full call trace, stdout/stderr logs, and stamped output for post-hoc inspection.",
|
|
12563
|
-
|
|
12564
|
-
project: z6.string().optional(),
|
|
12565
|
-
runId: z6.string()
|
|
12566
|
-
},
|
|
13206
|
+
GetScriptRunInputSchema.shape,
|
|
12567
13207
|
async ({ project, runId }) => {
|
|
12568
13208
|
const resolved = project ? await resolveProjectId(project) : projectId;
|
|
12569
13209
|
try {
|