@earendil-works/pi-durable 1.4.0 → 1.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +204 -0
- package/README.md +195 -85
- package/dist/codemode/codemode.d.ts +6 -5
- package/dist/codemode/codemode.d.ts.map +1 -1
- package/dist/codemode/codemode.js +10 -49
- package/dist/codemode/codemode.js.map +1 -1
- package/dist/codemode/models.d.ts +2 -1
- package/dist/codemode/models.d.ts.map +1 -1
- package/dist/codemode/models.js +4 -4
- package/dist/codemode/models.js.map +1 -1
- package/dist/documents.d.ts +1 -1
- package/dist/documents.d.ts.map +1 -1
- package/dist/documents.js +1 -1
- package/dist/documents.js.map +1 -1
- package/dist/entries.d.ts +1 -1
- package/dist/entries.d.ts.map +1 -1
- package/dist/entries.js.map +1 -1
- package/dist/env/index.d.ts +13 -11
- package/dist/env/index.d.ts.map +1 -1
- package/dist/env/index.js.map +1 -1
- package/dist/env/node-watch.d.ts +4 -4
- package/dist/env/node-watch.d.ts.map +1 -1
- package/dist/env/node-watch.js +18 -16
- package/dist/env/node-watch.js.map +1 -1
- package/dist/env/node.d.ts +3 -3
- package/dist/env/node.d.ts.map +1 -1
- package/dist/env/node.js +1 -1
- package/dist/env/node.js.map +1 -1
- package/dist/errors.d.ts +18 -2
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +26 -3
- package/dist/errors.js.map +1 -1
- package/dist/harness/agent.d.ts.map +1 -1
- package/dist/harness/agent.js +37 -3
- package/dist/harness/agent.js.map +1 -1
- package/dist/harness/compaction.d.ts +8 -3
- package/dist/harness/compaction.d.ts.map +1 -1
- package/dist/harness/compaction.js +40 -11
- package/dist/harness/compaction.js.map +1 -1
- package/dist/harness/context.d.ts +24 -8
- package/dist/harness/context.d.ts.map +1 -1
- package/dist/harness/context.js +71 -25
- package/dist/harness/context.js.map +1 -1
- package/dist/harness/define.d.ts +8 -4
- package/dist/harness/define.d.ts.map +1 -1
- package/dist/harness/define.js +4 -0
- package/dist/harness/define.js.map +1 -1
- package/dist/harness/generation.d.ts +39 -6
- package/dist/harness/generation.d.ts.map +1 -1
- package/dist/harness/generation.js +451 -100
- package/dist/harness/generation.js.map +1 -1
- package/dist/harness/harness.d.ts +3 -1
- package/dist/harness/harness.d.ts.map +1 -1
- package/dist/harness/harness.js +87 -62
- package/dist/harness/harness.js.map +1 -1
- package/dist/harness/inbox.d.ts +7 -2
- package/dist/harness/inbox.d.ts.map +1 -1
- package/dist/harness/inbox.js +5 -2
- package/dist/harness/inbox.js.map +1 -1
- package/dist/harness/json.d.ts +21 -5
- package/dist/harness/json.d.ts.map +1 -1
- package/dist/harness/json.js +23 -5
- package/dist/harness/json.js.map +1 -1
- package/dist/harness/live.d.ts +124 -17
- package/dist/harness/live.d.ts.map +1 -1
- package/dist/harness/live.js +93 -12
- package/dist/harness/live.js.map +1 -1
- package/dist/harness/partial-changes.d.ts +54 -0
- package/dist/harness/partial-changes.d.ts.map +1 -0
- package/dist/harness/partial-changes.js +163 -0
- package/dist/harness/partial-changes.js.map +1 -0
- package/dist/harness/prompt.d.ts +1 -1
- package/dist/harness/prompt.d.ts.map +1 -1
- package/dist/harness/prompt.js.map +1 -1
- package/dist/harness/provider.d.ts +1 -1
- package/dist/harness/provider.d.ts.map +1 -1
- package/dist/harness/provider.js.map +1 -1
- package/dist/harness/registry-reader.d.ts +11 -0
- package/dist/harness/registry-reader.d.ts.map +1 -0
- package/dist/harness/registry-reader.js +25 -0
- package/dist/harness/registry-reader.js.map +1 -0
- package/dist/harness/scheduler.d.ts +48 -20
- package/dist/harness/scheduler.d.ts.map +1 -1
- package/dist/harness/scheduler.js +1006 -380
- package/dist/harness/scheduler.js.map +1 -1
- package/dist/harness/submissions.d.ts +18 -11
- package/dist/harness/submissions.d.ts.map +1 -1
- package/dist/harness/submissions.js +63 -26
- package/dist/harness/submissions.js.map +1 -1
- package/dist/harness/task-graph.d.ts +14 -9
- package/dist/harness/task-graph.d.ts.map +1 -1
- package/dist/harness/task-graph.js +38 -28
- package/dist/harness/task-graph.js.map +1 -1
- package/dist/harness/telemetry.d.ts +11 -11
- package/dist/harness/telemetry.d.ts.map +1 -1
- package/dist/harness/telemetry.js +7 -7
- package/dist/harness/telemetry.js.map +1 -1
- package/dist/harness/tool.d.ts +3 -1
- package/dist/harness/tool.d.ts.map +1 -1
- package/dist/harness/tool.js +172 -56
- package/dist/harness/tool.js.map +1 -1
- package/dist/harness/transcript.d.ts +72 -0
- package/dist/harness/transcript.d.ts.map +1 -0
- package/dist/harness/transcript.js +264 -0
- package/dist/harness/transcript.js.map +1 -0
- package/dist/harness/types.d.ts +237 -61
- package/dist/harness/types.d.ts.map +1 -1
- package/dist/harness/types.js.map +1 -1
- package/dist/harness/usage.d.ts +2 -1
- package/dist/harness/usage.d.ts.map +1 -1
- package/dist/harness/usage.js +1 -1
- package/dist/harness/usage.js.map +1 -1
- package/dist/harness/util.d.ts +4 -2
- package/dist/harness/util.d.ts.map +1 -1
- package/dist/harness/util.js +9 -0
- package/dist/harness/util.js.map +1 -1
- package/dist/harness/view.d.ts +44 -22
- package/dist/harness/view.d.ts.map +1 -1
- package/dist/harness/view.js +130 -71
- package/dist/harness/view.js.map +1 -1
- package/dist/index.d.ts +9 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/search.d.ts +19 -3
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +107 -44
- package/dist/search.js.map +1 -1
- package/dist/session/cached-storage.d.ts +72 -0
- package/dist/session/cached-storage.d.ts.map +1 -0
- package/dist/session/cached-storage.js +269 -0
- package/dist/session/cached-storage.js.map +1 -0
- package/dist/session/conversation-tails.d.ts +33 -0
- package/dist/session/conversation-tails.d.ts.map +1 -0
- package/dist/session/conversation-tails.js +101 -0
- package/dist/session/conversation-tails.js.map +1 -0
- package/dist/session/forks.d.ts +1 -1
- package/dist/session/forks.d.ts.map +1 -1
- package/dist/session/forks.js.map +1 -1
- package/dist/session/keys.d.ts +69 -0
- package/dist/session/keys.d.ts.map +1 -0
- package/dist/session/keys.js +161 -0
- package/dist/session/keys.js.map +1 -0
- package/dist/session/session.d.ts +169 -26
- package/dist/session/session.d.ts.map +1 -1
- package/dist/session/session.js +1029 -171
- package/dist/session/session.js.map +1 -1
- package/dist/session/transaction.d.ts +84 -5
- package/dist/session/transaction.d.ts.map +1 -1
- package/dist/session/transaction.js +227 -40
- package/dist/session/transaction.js.map +1 -1
- package/dist/session/writer.d.ts +74 -0
- package/dist/session/writer.d.ts.map +1 -0
- package/dist/session/writer.js +294 -0
- package/dist/session/writer.js.map +1 -0
- package/dist/storage/indexeddb.d.ts +12 -3
- package/dist/storage/indexeddb.d.ts.map +1 -1
- package/dist/storage/indexeddb.js +91 -41
- package/dist/storage/indexeddb.js.map +1 -1
- package/dist/storage/jsonl/index.d.ts +1 -1
- package/dist/storage/jsonl/index.d.ts.map +1 -1
- package/dist/storage/jsonl/index.js +1 -1
- package/dist/storage/jsonl/index.js.map +1 -1
- package/dist/storage/jsonl/node.d.ts +3 -3
- package/dist/storage/jsonl/node.d.ts.map +1 -1
- package/dist/storage/jsonl/node.js +2 -2
- package/dist/storage/jsonl/node.js.map +1 -1
- package/dist/storage/jsonl/storage.d.ts +46 -5
- package/dist/storage/jsonl/storage.d.ts.map +1 -1
- package/dist/storage/jsonl/storage.js +158 -43
- package/dist/storage/jsonl/storage.js.map +1 -1
- package/dist/storage/memory.d.ts +9 -3
- package/dist/storage/memory.d.ts.map +1 -1
- package/dist/storage/memory.js +28 -2
- package/dist/storage/memory.js.map +1 -1
- package/dist/storage/sqlite/commit.d.ts +52 -0
- package/dist/storage/sqlite/commit.d.ts.map +1 -0
- package/dist/storage/sqlite/commit.js +371 -0
- package/dist/storage/sqlite/commit.js.map +1 -0
- package/dist/storage/sqlite/rows.d.ts +33 -0
- package/dist/storage/sqlite/rows.d.ts.map +1 -0
- package/dist/storage/sqlite/rows.js +53 -0
- package/dist/storage/sqlite/rows.js.map +1 -0
- package/dist/storage/sqlite/statements.d.ts +13 -0
- package/dist/storage/sqlite/statements.d.ts.map +1 -0
- package/dist/storage/sqlite/statements.js +88 -0
- package/dist/storage/sqlite/statements.js.map +1 -0
- package/dist/storage/sqlite/storage.d.ts +23 -10
- package/dist/storage/sqlite/storage.d.ts.map +1 -1
- package/dist/storage/sqlite/storage.js +120 -261
- package/dist/storage/sqlite/storage.js.map +1 -1
- package/dist/storage/store/commit.d.ts +33 -0
- package/dist/storage/store/commit.d.ts.map +1 -0
- package/dist/storage/store/commit.js +286 -0
- package/dist/storage/store/commit.js.map +1 -0
- package/dist/storage/store/documents.d.ts +43 -0
- package/dist/storage/store/documents.d.ts.map +1 -0
- package/dist/storage/store/documents.js +102 -0
- package/dist/storage/store/documents.js.map +1 -0
- package/dist/storage/store/index.d.ts +2 -0
- package/dist/storage/store/index.d.ts.map +1 -0
- package/dist/storage/store/index.js +2 -0
- package/dist/storage/store/index.js.map +1 -0
- package/dist/storage/store/queries.d.ts +49 -0
- package/dist/storage/store/queries.d.ts.map +1 -0
- package/dist/storage/store/queries.js +93 -0
- package/dist/storage/store/queries.js.map +1 -0
- package/dist/storage/store/storage.d.ts +60 -0
- package/dist/storage/store/storage.d.ts.map +1 -0
- package/dist/storage/store/storage.js +438 -0
- package/dist/storage/store/storage.js.map +1 -0
- package/dist/storage/store/tables.d.ts +54 -0
- package/dist/storage/store/tables.d.ts.map +1 -0
- package/dist/storage/store/tables.js +108 -0
- package/dist/storage/store/tables.js.map +1 -0
- package/dist/testing/commit-writes.d.ts +5 -0
- package/dist/testing/commit-writes.d.ts.map +1 -0
- package/dist/testing/commit-writes.js +12 -0
- package/dist/testing/commit-writes.js.map +1 -0
- package/dist/testing/env-conformance.js +7 -7
- package/dist/testing/env-conformance.js.map +1 -1
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +1 -0
- package/dist/testing/index.js.map +1 -1
- package/dist/testing/storage-benchmark.d.ts.map +1 -1
- package/dist/testing/storage-benchmark.js +18 -17
- package/dist/testing/storage-benchmark.js.map +1 -1
- package/dist/testing/storage-conformance.d.ts.map +1 -1
- package/dist/testing/storage-conformance.js +354 -69
- package/dist/testing/storage-conformance.js.map +1 -1
- package/dist/tool-search/tool-search.d.ts +8 -14
- package/dist/tool-search/tool-search.d.ts.map +1 -1
- package/dist/tool-search/tool-search.js +25 -13
- package/dist/tool-search/tool-search.js.map +1 -1
- package/dist/tools/bash.d.ts +13 -13
- package/dist/tools/bash.d.ts.map +1 -1
- package/dist/tools/bash.js +16 -15
- package/dist/tools/bash.js.map +1 -1
- package/dist/tools/edit.d.ts +7 -7
- package/dist/tools/edit.d.ts.map +1 -1
- package/dist/tools/edit.js +9 -9
- package/dist/tools/edit.js.map +1 -1
- package/dist/tools/file-mutation-queue.d.ts +1 -1
- package/dist/tools/file-mutation-queue.d.ts.map +1 -1
- package/dist/tools/file-mutation-queue.js.map +1 -1
- package/dist/tools/index.d.ts +32 -32
- package/dist/tools/path-utils.d.ts +1 -1
- package/dist/tools/path-utils.d.ts.map +1 -1
- package/dist/tools/path-utils.js.map +1 -1
- package/dist/tools/read.d.ts +6 -6
- package/dist/tools/read.d.ts.map +1 -1
- package/dist/tools/read.js +19 -8
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/write.d.ts +4 -4
- package/dist/tools/write.d.ts.map +1 -1
- package/dist/tools/write.js +5 -5
- package/dist/tools/write.js.map +1 -1
- package/dist/types.d.ts +228 -78
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +19 -12
- package/dist/harness/events.d.ts +0 -186
- package/dist/harness/events.d.ts.map +0 -1
- package/dist/harness/events.js +0 -373
- package/dist/harness/events.js.map +0 -1
- package/dist/session/observation.d.ts +0 -42
- package/dist/session/observation.d.ts.map +0 -1
- package/dist/session/observation.js +0 -281
- package/dist/session/observation.js.map +0 -1
|
@@ -1,9 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The `tool_search` tool, a copy of the coding agent's: the model searches the deferred tools it is not offered yet,
|
|
3
|
-
* and the matches are loaded with `control.addTools`, so the next request offers them. Loading writes the
|
|
4
|
-
* conversation's `modelTools` (its `add`), so loaded tools stay offered on that branch, also after a compaction.
|
|
5
|
-
*/
|
|
6
|
-
import { Type } from "@earendil-works/pi-ai";
|
|
7
1
|
import type { ToolRegistration } from "../harness/types.ts";
|
|
8
2
|
export declare const TOOL_SEARCH_TOOL_NAME = "tool_search";
|
|
9
3
|
export declare const DEFAULT_TOOL_SEARCH_LIMIT = 8;
|
|
@@ -11,13 +5,13 @@ export declare const DEFAULT_TOOL_SEARCH_LIMIT = 8;
|
|
|
11
5
|
export type ToolSearchToolDetails = {
|
|
12
6
|
loaded: string[];
|
|
13
7
|
};
|
|
14
|
-
export declare function createToolSearchTool(): ToolRegistration<
|
|
15
|
-
query:
|
|
16
|
-
limit
|
|
17
|
-
}>, import("@earendil-works/chord").JsonValue>;
|
|
8
|
+
export declare function createToolSearchTool(): ToolRegistration<import("@earendil-works/pi-schema").Schema<{
|
|
9
|
+
query: string;
|
|
10
|
+
limit?: number | undefined;
|
|
11
|
+
}>, import("@earendil-works/chord/json").JsonValue>;
|
|
18
12
|
/** The `tool_search` extension: install it and select it where the model should find deferred tools. */
|
|
19
|
-
export declare function createToolSearchExtension(): import("../harness/types.ts").Extension<ToolRegistration<
|
|
20
|
-
query:
|
|
21
|
-
limit
|
|
22
|
-
}>, import("@earendil-works/chord").JsonValue>>;
|
|
13
|
+
export declare function createToolSearchExtension(): import("../harness/types.ts").Extension<ToolRegistration<import("@earendil-works/pi-schema").Schema<{
|
|
14
|
+
query: string;
|
|
15
|
+
limit?: number | undefined;
|
|
16
|
+
}>, import("@earendil-works/chord/json").JsonValue>>;
|
|
23
17
|
//# sourceMappingURL=tool-search.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-search.d.ts","sourceRoot":"","sources":["../../src/tool-search/tool-search.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"tool-search.d.ts","sourceRoot":"","sources":["../../src/tool-search/tool-search.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAG5D,eAAO,MAAM,qBAAqB,gBAAgB,CAAC;AACnD,eAAO,MAAM,yBAAyB,IAAI,CAAC;AAa3C,yDAAyD;AACzD,MAAM,MAAM,qBAAqB,GAAG;IAAE,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAyCzD,wBAAgB,oBAAoB;;;oDAgCnC;AAED,wGAAwG;AACxG,wBAAgB,yBAAyB;;;qDAExC"}
|
|
@@ -3,44 +3,56 @@
|
|
|
3
3
|
* and the matches are loaded with `control.addTools`, so the next request offers them. Loading writes the
|
|
4
4
|
* conversation's `modelTools` (its `add`), so loaded tools stay offered on that branch, also after a compaction.
|
|
5
5
|
*/
|
|
6
|
-
import {
|
|
6
|
+
import { resolveSchemaRef } from "@earendil-works/pi-codemode/declarations";
|
|
7
|
+
import { num, obj, opt, str } from "@earendil-works/pi-schema";
|
|
7
8
|
import { defineExtension, defineTool } from "../harness/define.js";
|
|
8
9
|
import { rankDocuments } from "../search.js";
|
|
9
10
|
export const TOOL_SEARCH_TOOL_NAME = "tool_search";
|
|
10
11
|
export const DEFAULT_TOOL_SEARCH_LIMIT = 8;
|
|
11
12
|
/** Fixed, so it does not change while deferred tools are registered, for example as MCP servers connect. */
|
|
12
13
|
const TOOL_SEARCH_DESCRIPTION = `# Tool discovery\n\nSearches over deferred tool metadata with BM25 and exposes matching tools for the next model call.\n\nSome of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${TOOL_SEARCH_TOOL_NAME}\`) to search for the required tools. For MCP tool discovery, always use \`${TOOL_SEARCH_TOOL_NAME}\`.`;
|
|
13
|
-
const toolSearchSchema =
|
|
14
|
-
query:
|
|
15
|
-
limit:
|
|
16
|
-
});
|
|
14
|
+
const toolSearchSchema = obj({
|
|
15
|
+
query: str({ description: "Search query for deferred tools." }),
|
|
16
|
+
limit: opt(num({ description: `Maximum number of tools to return. Defaults to ${DEFAULT_TOOL_SEARCH_LIMIT}.` })),
|
|
17
|
+
}, { open: true });
|
|
17
18
|
function isObject(value) {
|
|
18
19
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
19
20
|
}
|
|
20
|
-
/**
|
|
21
|
-
|
|
21
|
+
/**
|
|
22
|
+
* Schema descriptions and property names, recursively, following local `$ref`s into `root`. `seen` holds the
|
|
23
|
+
* subschemas already reached through a reference, so recursive and shared definitions are read once, and
|
|
24
|
+
* definitions no property references are not read.
|
|
25
|
+
*/
|
|
26
|
+
function schemaText(schema, root, parts, seen) {
|
|
22
27
|
if (!isObject(schema))
|
|
23
28
|
return;
|
|
29
|
+
if (typeof schema.$ref === "string") {
|
|
30
|
+
const target = resolveSchemaRef(schema.$ref, root);
|
|
31
|
+
if (isObject(target) && !seen.has(target)) {
|
|
32
|
+
seen.add(target);
|
|
33
|
+
schemaText(target, root, parts, seen);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
24
36
|
if (typeof schema.description === "string")
|
|
25
37
|
parts.push(schema.description);
|
|
26
38
|
if (isObject(schema.properties)) {
|
|
27
39
|
for (const [name, property] of Object.entries(schema.properties)) {
|
|
28
40
|
parts.push(name);
|
|
29
|
-
schemaText(property, parts);
|
|
41
|
+
schemaText(property, root, parts, seen);
|
|
30
42
|
}
|
|
31
43
|
}
|
|
32
|
-
schemaText(schema.items, parts);
|
|
44
|
+
schemaText(schema.items, root, parts, seen);
|
|
33
45
|
for (const key of ["anyOf", "oneOf", "allOf"]) {
|
|
34
46
|
const variants = schema[key];
|
|
35
47
|
if (Array.isArray(variants))
|
|
36
48
|
for (const variant of variants)
|
|
37
|
-
schemaText(variant, parts);
|
|
49
|
+
schemaText(variant, root, parts, seen);
|
|
38
50
|
}
|
|
39
51
|
}
|
|
40
|
-
/** Search text of a tool: its
|
|
52
|
+
/** Search text of a tool: its description and its parameters' names and descriptions; the ranker reads the name. */
|
|
41
53
|
function searchText(tool) {
|
|
42
|
-
const parts = [tool.
|
|
43
|
-
schemaText(tool.parameters, parts);
|
|
54
|
+
const parts = [tool.description];
|
|
55
|
+
schemaText(tool.parameters, tool.parameters, parts, new Set([tool.parameters]));
|
|
44
56
|
return parts.filter((part) => part.trim() !== "").join(" ");
|
|
45
57
|
}
|
|
46
58
|
export function createToolSearchTool() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-search.js","sourceRoot":"","sources":["../../src/tool-search/tool-search.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"tool-search.js","sourceRoot":"","sources":["../../src/tool-search/tool-search.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AAC5E,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAEnE,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,MAAM,CAAC,MAAM,qBAAqB,GAAG,aAAa,CAAC;AACnD,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,CAAC;AAE3C,4GAA4G;AAC5G,MAAM,uBAAuB,GAAG,yPAAyP,qBAAqB,8EAA8E,qBAAqB,KAAK,CAAC;AAEvZ,MAAM,gBAAgB,GAAG,GAAG,CAC3B;IACC,KAAK,EAAE,GAAG,CAAC,EAAE,WAAW,EAAE,kCAAkC,EAAE,CAAC;IAC/D,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,EAAE,WAAW,EAAE,kDAAkD,yBAAyB,GAAG,EAAE,CAAC,CAAC;CAChH,EACD,EAAE,IAAI,EAAE,IAAI,EAAE,CAC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AAC,EAAE,OAAO,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,CAAC;aACjE,CAAC;QACH,CAAC;KACD,CAAC,CAAC;AACJ,CAAC;AAED,wGAAwG;AACxG,MAAM,UAAU,yBAAyB;IACxC,OAAO,eAAe,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,KAAK,EAAE,CAAC,oBAAoB,EAAE,CAAC,EAAE,CAAC,CAAC;AAClF,CAAC","sourcesContent":["/**\n * The `tool_search` tool, a copy of the coding agent's: the model searches the deferred tools it is not offered yet,\n * and the matches are loaded with `control.addTools`, so the next request offers them. Loading writes the\n * conversation's `modelTools` (its `add`), so loaded tools stay offered on that branch, also after a compaction.\n */\nimport { resolveSchemaRef } from \"@earendil-works/pi-codemode/declarations\";\nimport { num, obj, opt, str } from \"@earendil-works/pi-schema\";\nimport { defineExtension, defineTool } from \"../harness/define.ts\";\nimport type { ToolRegistration } from \"../harness/types.ts\";\nimport { rankDocuments } from \"../search.ts\";\n\nexport const TOOL_SEARCH_TOOL_NAME = \"tool_search\";\nexport const DEFAULT_TOOL_SEARCH_LIMIT = 8;\n\n/** Fixed, so it does not change while deferred tools are registered, for example as MCP servers connect. */\nconst TOOL_SEARCH_DESCRIPTION = `# Tool discovery\\n\\nSearches over deferred tool metadata with BM25 and exposes matching tools for the next model call.\\n\\nSome of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\\`${TOOL_SEARCH_TOOL_NAME}\\`) to search for the required tools. For MCP tool discovery, always use \\`${TOOL_SEARCH_TOOL_NAME}\\`.`;\n\nconst toolSearchSchema = obj(\n\t{\n\t\tquery: str({ description: \"Search query for deferred tools.\" }),\n\t\tlimit: opt(num({ description: `Maximum number of tools to return. Defaults to ${DEFAULT_TOOL_SEARCH_LIMIT}.` })),\n\t},\n\t{ open: true },\n);\n\n/** `tool_search` result details: the tools it loaded. */\nexport type ToolSearchToolDetails = { loaded: string[] };\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Schema descriptions and property names, recursively, following local `$ref`s into `root`. `seen` holds the\n * subschemas already reached through a reference, so recursive and shared definitions are read once, and\n * definitions no property references are not read.\n */\nfunction schemaText(schema: unknown, root: unknown, parts: string[], seen: Set<unknown>): void {\n\tif (!isObject(schema)) return;\n\tif (typeof schema.$ref === \"string\") {\n\t\tconst target = resolveSchemaRef(schema.$ref, root);\n\t\tif (isObject(target) && !seen.has(target)) {\n\t\t\tseen.add(target);\n\t\t\tschemaText(target, root, parts, seen);\n\t\t}\n\t}\n\tif (typeof schema.description === \"string\") parts.push(schema.description);\n\tif (isObject(schema.properties)) {\n\t\tfor (const [name, property] of Object.entries(schema.properties)) {\n\t\t\tparts.push(name);\n\t\t\tschemaText(property, root, parts, seen);\n\t\t}\n\t}\n\tschemaText(schema.items, root, parts, seen);\n\tfor (const key of [\"anyOf\", \"oneOf\", \"allOf\"]) {\n\t\tconst variants = schema[key];\n\t\tif (Array.isArray(variants)) for (const variant of variants) schemaText(variant, root, parts, seen);\n\t}\n}\n\n/** Search text of a tool: its description and its parameters' names and descriptions; the ranker reads the name. */\nfunction searchText(tool: ToolRegistration): string {\n\tconst parts = [tool.description];\n\tschemaText(tool.parameters, tool.parameters, parts, new Set([tool.parameters]));\n\treturn parts.filter((part) => part.trim() !== \"\").join(\" \");\n}\n\nexport function createToolSearchTool() {\n\treturn defineTool({\n\t\tname: TOOL_SEARCH_TOOL_NAME,\n\t\tdescription: TOOL_SEARCH_DESCRIPTION,\n\t\tparameters: toolSearchSchema,\n\t\t// Searching changes what the model is offered; scripts have their own `searchTools()`.\n\t\tcallers: [\"model\"],\n\t\treplay: \"safe\",\n\t\tasync execute({ query, limit }, api, context) {\n\t\t\tif (query.trim() === \"\") throw new Error(\"query must not be empty\");\n\t\t\tconst max = limit ?? DEFAULT_TOOL_SEARCH_LIMIT;\n\t\t\tif (!Number.isInteger(max) || max <= 0) throw new Error(\"limit must be a positive integer\");\n\t\t\tconst candidates = (await api.agent(context)).deferred;\n\t\t\tconst documents = candidates.map((tool) => ({ name: tool.name, text: searchText(tool) }));\n\t\t\tconst loaded = rankDocuments(query, documents, max);\n\t\t\tconst text =\n\t\t\t\tloaded.length === 0\n\t\t\t\t\t? \"No matching tools found.\"\n\t\t\t\t\t: `Loaded ${loaded.length} tool${loaded.length === 1 ? \"\" : \"s\"}. They are available from your next call:\\n${loaded\n\t\t\t\t\t\t\t.map((name) => {\n\t\t\t\t\t\t\t\tconst description = candidates.find((tool) => tool.name === name)?.description ?? \"\";\n\t\t\t\t\t\t\t\treturn `- ${name}: ${description.trim().split(/\\r?\\n/)[0]}`;\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.join(\"\\n\")}`;\n\t\t\tconst details: ToolSearchToolDetails = { loaded };\n\t\t\treturn {\n\t\t\t\toutput: [{ type: \"text\", text }],\n\t\t\t\tdetails,\n\t\t\t\t...(loaded.length === 0 ? {} : { control: { addTools: loaded } }),\n\t\t\t};\n\t\t},\n\t});\n}\n\n/** The `tool_search` extension: install it and select it where the model should find deferred tools. */\nexport function createToolSearchExtension() {\n\treturn defineExtension({ name: \"tool-search\", tools: [createToolSearchTool()] });\n}\n"]}
|
package/dist/tools/bash.d.ts
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import type { Context } from "@earendil-works/chord";
|
|
2
|
-
import { type Static
|
|
1
|
+
import type { Context } from "@earendil-works/chord/context";
|
|
2
|
+
import { type Static } from "@earendil-works/pi-schema";
|
|
3
3
|
import type { ToolExecutionApi, ToolRegistration } from "../harness/types.ts";
|
|
4
|
-
declare const bashSchema:
|
|
5
|
-
command:
|
|
6
|
-
timeout
|
|
4
|
+
declare const bashSchema: import("@earendil-works/pi-schema").Schema<{
|
|
5
|
+
command: string;
|
|
6
|
+
timeout?: number | undefined;
|
|
7
7
|
}>;
|
|
8
|
-
declare const powershellSchema:
|
|
9
|
-
command:
|
|
10
|
-
timeout
|
|
8
|
+
declare const powershellSchema: import("@earendil-works/pi-schema").Schema<{
|
|
9
|
+
command: string;
|
|
10
|
+
timeout?: number | undefined;
|
|
11
11
|
}>;
|
|
12
12
|
/** What a program that calls `bash` or `powershell` receives. */
|
|
13
|
-
declare const shellStructuredOutputSchema:
|
|
14
|
-
output:
|
|
15
|
-
truncated:
|
|
16
|
-
fullOutputPath
|
|
17
|
-
exitCode:
|
|
13
|
+
declare const shellStructuredOutputSchema: import("@earendil-works/pi-schema").Schema<{
|
|
14
|
+
output: string;
|
|
15
|
+
truncated: boolean;
|
|
16
|
+
fullOutputPath?: string | undefined;
|
|
17
|
+
exitCode: number;
|
|
18
18
|
}>;
|
|
19
19
|
export type BashToolInput = Static<typeof bashSchema>;
|
|
20
20
|
export type PowerShellToolInput = Static<typeof powershellSchema>;
|
package/dist/tools/bash.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../src/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../src/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAC7D,OAAO,EAAuB,KAAK,MAAM,EAAO,MAAM,2BAA2B,CAAC;AAElF,OAAO,KAAK,EAAE,gBAAgB,EAAuB,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAOnG,QAAA,MAAM,UAAU;;;EAMf,CAAC;AAEF,QAAA,MAAM,gBAAgB;;;EAMrB,CAAC;AAEF,iEAAiE;AACjE,QAAA,MAAM,2BAA2B;;;;;EAQhC,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AACtD,MAAM,MAAM,mBAAmB,GAAG,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAClE,MAAM,MAAM,qBAAqB,GAAG,MAAM,CAAC,OAAO,2BAA2B,CAAC,CAAC;AAE/E,6GAA6G;AAC7G,MAAM,WAAW,aAAa;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC5B,UAAU,EAAE,OAAO,CAAC;CACpB;AAED,MAAM,MAAM,WAAW,GAAG,CAAC,SAAS,EAAE,aAAa,EAAE,GAAG,EAAE,gBAAgB,EAAE,OAAO,EAAE,OAAO,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAEtH,MAAM,WAAW,eAAe;IAC/B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,OAAO,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,MAAM,WAAW,qBAAqB;IACrC,qCAAqC;IACrC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,sHAAsH;IACtH,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7B;AAqFD;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,gBAAgB,CAAC,OAAO,UAAU,CAAC,CAa7F;AAMD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,CAAC,EAAE,qBAAqB,GAAG,gBAAgB,CAAC,OAAO,gBAAgB,CAAC,CAgB/G"}
|
package/dist/tools/bash.js
CHANGED
|
@@ -1,23 +1,24 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { bool, num, obj, opt, str } from "@earendil-works/pi-schema";
|
|
2
2
|
import { defineTool } from "../harness/define.js";
|
|
3
3
|
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES } from "../truncate.js";
|
|
4
4
|
import { requireEnv } from "./env.js";
|
|
5
5
|
const MAX_TIMEOUT_SECONDS = 2_147_483_647 / 1000;
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
})
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
})
|
|
6
|
+
// Open objects, as the tools accepted extra arguments when their schemas were TypeBox's.
|
|
7
|
+
const bashSchema = obj({
|
|
8
|
+
command: str({ description: "Bash command to execute" }),
|
|
9
|
+
timeout: opt(num({ description: "Timeout in seconds (optional, no default timeout)" })),
|
|
10
|
+
}, { open: true });
|
|
11
|
+
const powershellSchema = obj({
|
|
12
|
+
command: str({ description: "PowerShell command to execute" }),
|
|
13
|
+
timeout: opt(num({ description: "Timeout in seconds (optional, no default timeout)" })),
|
|
14
|
+
}, { open: true });
|
|
14
15
|
/** What a program that calls `bash` or `powershell` receives. */
|
|
15
|
-
const shellStructuredOutputSchema =
|
|
16
|
-
output:
|
|
17
|
-
truncated:
|
|
18
|
-
fullOutputPath:
|
|
19
|
-
exitCode:
|
|
20
|
-
});
|
|
16
|
+
const shellStructuredOutputSchema = obj({
|
|
17
|
+
output: str({ description: "Combined stdout and stderr: the retained tail, as the model sees it" }),
|
|
18
|
+
truncated: bool({ description: "Whether earlier output was dropped" }),
|
|
19
|
+
fullOutputPath: opt(str({ description: "File with the complete output, when it was spilled" })),
|
|
20
|
+
exitCode: num(),
|
|
21
|
+
}, { open: true });
|
|
21
22
|
function validateTimeout(timeout) {
|
|
22
23
|
if (timeout === undefined)
|
|
23
24
|
return;
|
package/dist/tools/bash.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash.js","sourceRoot":"","sources":["../../src/tools/bash.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAEtC,MAAM,m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port { defineTool } from \"../harness/define.ts\";\nimport type { ToolExecutionApi, ToolExecutionResult, ToolRegistration } from \"../harness/types.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES } from \"../truncate.ts\";\nimport { requireEnv } from \"./env.ts\";\n\nconst MAX_TIMEOUT_SECONDS = 2_147_483_647 / 1000;\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Bash command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n});\n\nconst powershellSchema = Type.Object({\n\tcommand: Type.String({ description: \"PowerShell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n});\n\n/** What a program that calls `bash` or `powershell` receives. */\nconst shellStructuredOutputSchema = Type.Object({\n\toutput: Type.String({ description: \"Combined stdout and stderr: the retained tail, as the model sees it\" }),\n\ttruncated: Type.Boolean({ description: \"Whether earlier output was dropped\" }),\n\tfullOutputPath: Type.Optional(Type.String({ description: \"File with the complete output, when it was spilled\" })),\n\texitCode: Type.Number(),\n});\n\nexport type BashToolInput = Static<typeof bashSchema>;\nexport type PowerShellToolInput = Static<typeof powershellSchema>;\nexport type ShellStructuredOutput = Static<typeof shellStructuredOutputSchema>;\n\n/** A command about to run, which `prepare` may change: the script, its working directory and environment. */\nexport interface BashExecution {\n\tcommand: string;\n\tcwd: string;\n\tenv: Record<string, string>;\n\tinheritEnv: boolean;\n}\n\nexport type BashPrepare = (execution: BashExecution, api: ToolExecutionApi, context: Context) => void | Promise<void>;\n\nexport interface BashToolOptions {\n\tcommandPrefix?: string;\n\tprepare?: BashPrepare;\n}\n\nexport interface PowerShellToolOptions {\n\t/** Lines run before each command. */\n\tcommandPrefix?: string;\n\tprepare?: BashPrepare;\n\t/** PowerShell programs to try in order; default `pwsh`, then `powershell`. A program that cannot start is skipped. */\n\tprograms?: readonly string[];\n}\n\nfunction validateTimeout(timeout: number | undefined): void {\n\tif (timeout === undefined) return;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\tif (timeout > MAX_TIMEOUT_SECONDS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n}\n\n/** The execution of one call: the command with its prefix, in the environment's working directory, then `prepare`. */\nasync function prepareExecution(\n\tcommand: string,\n\toptions: { commandPrefix?: string; prepare?: BashPrepare } | undefined,\n\tapi: ToolExecutionApi,\n\tcontext: Context,\n): Promise<BashExecution> {\n\tconst execution: BashExecution = {\n\t\tcommand: options?.commandPrefix ? `${options.commandPrefix}\\n${command}` : command,\n\t\tcwd: requireEnv(api).cwd,\n\t\tenv: {},\n\t\tinheritEnv: true,\n\t};\n\tawait options?.prepare?.(execution, api, context);\n\treturn execution;\n}\n\n/**\n * Run each command form in turn until one starts, streaming output to `api.output()` within the retained window, and\n * turn the result into the tool's result: a spill diagnostic, an error result for a nonzero exit, and a thrown error for\n * a failure such as a timeout. The structured output repeats the retained output with the exit code.\n */\nasync function runCommand(\n\tcommands: readonly (string | readonly string[])[],\n\texecution: BashExecution,\n\ttimeout: number | undefined,\n\tapi: ToolExecutionApi,\n\tcontext: Context,\n): Promise<ToolExecutionResult> {\n\tconst env = requireEnv(api);\n\tlet result: Awaited<ReturnType<typeof env.exec>> | undefined;\n\tfor (const command of commands) {\n\t\tresult = await env.exec(\n\t\t\tcommand,\n\t\t\t{\n\t\t\t\tcwd: execution.cwd,\n\t\t\t\tenv: execution.env,\n\t\t\t\tinheritEnv: execution.inheritEnv,\n\t\t\t\t...(timeout === undefined ? {} : { timeout }),\n\t\t\t\tonOutput: (text, _context, info) => api.output(text, info.skipped),\n\t\t\t\tspill: { afterBytes: DEFAULT_MAX_BYTES, afterLines: DEFAULT_MAX_LINES },\n\t\t\t\t// An environment may then omit output outside the retained tail and report the omission.\n\t\t\t\t...(api.outputWindow === undefined ? {} : { window: api.outputWindow }),\n\t\t\t},\n\t\t\tcontext,\n\t\t);\n\t\t// A program that could not start produced no output; the next form may.\n\t\tif (result.ok || result.error.code !== \"spawn_error\") break;\n\t}\n\tif (result === undefined) throw new Error(\"No command to run\");\n\tconst spillPath = result.ok ? result.value.spillPath : result.error.spillPath;\n\tif (spillPath !== undefined) {\n\t\tapi.diagnostic({ severity: \"info\", code: \"full_output\", message: `Full output: ${spillPath}` });\n\t}\n\tif (!result.ok) {\n\t\tif (result.error.code === \"aborted\" && context.abortSignal?.aborted) throw result.error;\n\t\tif (result.error.code === \"timeout\") throw new Error(`Command timed out after ${timeout} seconds`);\n\t\tif (result.error.code === \"aborted\") throw new Error(\"Command aborted\");\n\t\tthrow result.error;\n\t}\n\tconst exitCode = result.value.exitCode;\n\tconst retained = api.retainedOutput();\n\tconst structuredOutput: ShellStructuredOutput = {\n\t\toutput: retained.text,\n\t\ttruncated: retained.truncated,\n\t\t...(spillPath === undefined ? {} : { fullOutputPath: spillPath }),\n\t\texitCode,\n\t};\n\tif (exitCode === 0) return { structuredOutput };\n\tconst exited = { severity: \"error\", code: \"exit_code\", message: `Command exited with code ${exitCode}` } as const;\n\treturn { structuredOutput, isError: true, diagnostics: [exited] };\n}\n\n/**\n * Runs a command through the environment's shell. Its output streams to `api.output()`, where the Harness keeps the\n * tail within the default limits; the result content is that retained output. The retained window goes to the\n * environment, which may omit output outside it and report how much it omitted, so dropped counts stay exact. Output\n * beyond the limits is spilled to a file whose path is reported as a diagnostic. A nonzero exit is an error result with\n * the exit code; a timeout throws, which makes an error result that still carries the output and diagnostics.\n */\nexport function createBashTool(options?: BashToolOptions): ToolRegistration<typeof bashSchema> {\n\treturn defineTool({\n\t\tname: \"bash\",\n\t\tdescription: `Execute a bash command in the current working directory. Returns combined stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tparameters: bashSchema,\n\t\tstructuredOutputSchema: shellStructuredOutputSchema,\n\t\toutputLimits: { retain: \"tail\" },\n\t\tasync execute(args, api, context) {\n\t\t\tvalidateTimeout(args.timeout);\n\t\t\tconst execution = await prepareExecution(args.command, options, api, context);\n\t\t\treturn runCommand([execution.command], execution, args.timeout, api, context);\n\t\t},\n\t});\n}\n\n/** Output in UTF-8 whatever the console's code page, as the coding agent's `powershell` tool does. */\nconst UTF8_OUTPUT = \"try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}\";\nconst POWERSHELL_ARGS = [\"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-Command\"] as const;\n\n/**\n * Runs a PowerShell command, like `bash` but through PowerShell instead of the environment's shell: `pwsh` (PowerShell\n * 7), else Windows PowerShell, started directly with the command as an argument, so no other shell parses it.\n */\nexport function createPowerShellTool(options?: PowerShellToolOptions): ToolRegistration<typeof powershellSchema> {\n\tconst programs = options?.programs ?? [\"pwsh\", \"powershell\"];\n\treturn defineTool({\n\t\tname: \"powershell\",\n\t\tdescription: `Execute a PowerShell command in the current working directory. Returns combined stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tparameters: powershellSchema,\n\t\tstructuredOutputSchema: shellStructuredOutputSchema,\n\t\toutputLimits: { retain: \"tail\" },\n\t\tasync execute(args, api, context) {\n\t\t\tvalidateTimeout(args.timeout);\n\t\t\tconst execution = await prepareExecution(args.command, options, api, context);\n\t\t\tconst script = `${UTF8_OUTPUT}\\n${execution.command}`;\n\t\t\tconst commands = programs.map((program) => [program, ...POWERSHELL_ARGS, script]);\n\t\t\treturn runCommand(commands, execution, args.timeout, api, context);\n\t\t},\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bash.js","sourceRoot":"","sources":["../../src/tools/bash.ts"],"names":[],"mappings":"AACA,OAAO,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AClF,OAAO,UAAU,CAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,OAAO,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;QACpE,CAAC;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { Context } from \"@earendil-works/chord/context\";\nimport { bool, num, obj, opt, type Static, str } from \"@earendil-works/pi-schema\";\nimport { defineTool } from \"../harness/define.ts\";\nimport type { ToolExecutionApi, ToolExecutionResult, ToolRegistration } from \"../harness/types.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES } from \"../truncate.ts\";\nimport { requireEnv } from \"./env.ts\";\n\nconst MAX_TIMEOUT_SECONDS = 2_147_483_647 / 1000;\n\n// Open objects, as the tools accepted extra arguments when their schemas were TypeBox's.\nconst bashSchema = obj(\n\t{\n\t\tcommand: str({ description: \"Bash command to execute\" }),\n\t\ttimeout: opt(num({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n\t},\n\t{ open: true },\n);\n\nconst powershellSchema = obj(\n\t{\n\t\tcommand: str({ description: \"PowerShell command to execute\" }),\n\t\ttimeout: opt(num({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n\t},\n\t{ open: true },\n);\n\n/** What a program that calls `bash` or `powershell` receives. */\nconst shellStructuredOutputSchema = obj(\n\t{\n\t\toutput: str({ description: \"Combined stdout and stderr: the retained tail, as the model sees it\" }),\n\t\ttruncated: bool({ description: \"Whether earlier output was dropped\" }),\n\t\tfullOutputPath: opt(str({ description: \"File with the complete output, when it was spilled\" })),\n\t\texitCode: num(),\n\t},\n\t{ open: true },\n);\n\nexport type BashToolInput = Static<typeof bashSchema>;\nexport type PowerShellToolInput = Static<typeof powershellSchema>;\nexport type ShellStructuredOutput = Static<typeof shellStructuredOutputSchema>;\n\n/** A command about to run, which `prepare` may change: the script, its working directory and environment. */\nexport interface BashExecution {\n\tcommand: string;\n\tcwd: string;\n\tenv: Record<string, string>;\n\tinheritEnv: boolean;\n}\n\nexport type BashPrepare = (execution: BashExecution, api: ToolExecutionApi, context: Context) => void | Promise<void>;\n\nexport interface BashToolOptions {\n\tcommandPrefix?: string;\n\tprepare?: BashPrepare;\n}\n\nexport interface PowerShellToolOptions {\n\t/** Lines run before each command. */\n\tcommandPrefix?: string;\n\tprepare?: BashPrepare;\n\t/** PowerShell programs to try in order; default `pwsh`, then `powershell`. A program that cannot start is skipped. */\n\tprograms?: readonly string[];\n}\n\nfunction validateTimeout(timeout: number | undefined): void {\n\tif (timeout === undefined) return;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\tif (timeout > MAX_TIMEOUT_SECONDS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n}\n\n/** The execution of one call: the command with its prefix, in the environment's working directory, then `prepare`. */\nasync function prepareExecution(\n\tcommand: string,\n\toptions: { commandPrefix?: string; prepare?: BashPrepare } | undefined,\n\tapi: ToolExecutionApi,\n\tcontext: Context,\n): Promise<BashExecution> {\n\tconst execution: BashExecution = {\n\t\tcommand: options?.commandPrefix ? `${options.commandPrefix}\\n${command}` : command,\n\t\tcwd: requireEnv(api).cwd,\n\t\tenv: {},\n\t\tinheritEnv: true,\n\t};\n\tawait options?.prepare?.(execution, api, context);\n\treturn execution;\n}\n\n/**\n * Run each command form in turn until one starts, streaming output to `api.output()` within the retained window, and\n * turn the result into the tool's result: a spill diagnostic, an error result for a nonzero exit, and a thrown error for\n * a failure such as a timeout. The structured output repeats the retained output with the exit code.\n */\nasync function runCommand(\n\tcommands: readonly (string | readonly string[])[],\n\texecution: BashExecution,\n\ttimeout: number | undefined,\n\tapi: ToolExecutionApi,\n\tcontext: Context,\n): Promise<ToolExecutionResult> {\n\tconst env = requireEnv(api);\n\tlet result: Awaited<ReturnType<typeof env.exec>> | undefined;\n\tfor (const command of commands) {\n\t\tresult = await env.exec(\n\t\t\tcommand,\n\t\t\t{\n\t\t\t\tcwd: execution.cwd,\n\t\t\t\tenv: execution.env,\n\t\t\t\tinheritEnv: execution.inheritEnv,\n\t\t\t\t...(timeout === undefined ? {} : { timeout }),\n\t\t\t\tonOutput: (text, _context, info) => api.output(text, info.skipped),\n\t\t\t\tspill: { afterBytes: DEFAULT_MAX_BYTES, afterLines: DEFAULT_MAX_LINES },\n\t\t\t\t// An environment may then omit output outside the retained tail and report the omission.\n\t\t\t\t...(api.outputWindow === undefined ? {} : { window: api.outputWindow }),\n\t\t\t},\n\t\t\tcontext,\n\t\t);\n\t\t// A program that could not start produced no output; the next form may.\n\t\tif (result.ok || result.error.code !== \"spawn_error\") break;\n\t}\n\tif (result === undefined) throw new Error(\"No command to run\");\n\tconst spillPath = result.ok ? result.value.spillPath : result.error.spillPath;\n\tif (spillPath !== undefined) {\n\t\tapi.diagnostic({ severity: \"info\", code: \"full_output\", message: `Full output: ${spillPath}` });\n\t}\n\tif (!result.ok) {\n\t\tif (result.error.code === \"aborted\" && context.abortSignal?.aborted) throw result.error;\n\t\tif (result.error.code === \"timeout\") throw new Error(`Command timed out after ${timeout} seconds`);\n\t\tif (result.error.code === \"aborted\") throw new Error(\"Command aborted\");\n\t\tthrow result.error;\n\t}\n\tconst exitCode = result.value.exitCode;\n\tconst retained = api.retainedOutput();\n\tconst structuredOutput: ShellStructuredOutput = {\n\t\toutput: retained.text,\n\t\ttruncated: retained.truncated,\n\t\t...(spillPath === undefined ? {} : { fullOutputPath: spillPath }),\n\t\texitCode,\n\t};\n\tif (exitCode === 0) return { structuredOutput };\n\tconst exited = { severity: \"error\", code: \"exit_code\", message: `Command exited with code ${exitCode}` } as const;\n\treturn { structuredOutput, isError: true, diagnostics: [exited] };\n}\n\n/**\n * Runs a command through the environment's shell. Its output streams to `api.output()`, where the Harness keeps the\n * tail within the default limits; the result content is that retained output. The retained window goes to the\n * environment, which may omit output outside it and report how much it omitted, so dropped counts stay exact. Output\n * beyond the limits is spilled to a file whose path is reported as a diagnostic. A nonzero exit is an error result with\n * the exit code; a timeout throws, which makes an error result that still carries the output and diagnostics.\n */\nexport function createBashTool(options?: BashToolOptions): ToolRegistration<typeof bashSchema> {\n\treturn defineTool({\n\t\tname: \"bash\",\n\t\tdescription: `Execute a bash command in the current working directory. Returns combined stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tparameters: bashSchema,\n\t\tstructuredOutputSchema: shellStructuredOutputSchema,\n\t\toutputLimits: { retain: \"tail\" },\n\t\tasync execute(args, api, context) {\n\t\t\tvalidateTimeout(args.timeout);\n\t\t\tconst execution = await prepareExecution(args.command, options, api, context);\n\t\t\treturn runCommand([execution.command], execution, args.timeout, api, context);\n\t\t},\n\t});\n}\n\n/** Output in UTF-8 whatever the console's code page, as the coding agent's `powershell` tool does. */\nconst UTF8_OUTPUT = \"try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}\";\nconst POWERSHELL_ARGS = [\"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-Command\"] as const;\n\n/**\n * Runs a PowerShell command, like `bash` but through PowerShell instead of the environment's shell: `pwsh` (PowerShell\n * 7), else Windows PowerShell, started directly with the command as an argument, so no other shell parses it.\n */\nexport function createPowerShellTool(options?: PowerShellToolOptions): ToolRegistration<typeof powershellSchema> {\n\tconst programs = options?.programs ?? [\"pwsh\", \"powershell\"];\n\treturn defineTool({\n\t\tname: \"powershell\",\n\t\tdescription: `Execute a PowerShell command in the current working directory. Returns combined stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tparameters: powershellSchema,\n\t\tstructuredOutputSchema: shellStructuredOutputSchema,\n\t\toutputLimits: { retain: \"tail\" },\n\t\tasync execute(args, api, context) {\n\t\t\tvalidateTimeout(args.timeout);\n\t\t\tconst execution = await prepareExecution(args.command, options, api, context);\n\t\t\tconst script = `${UTF8_OUTPUT}\\n${execution.command}`;\n\t\t\tconst commands = programs.map((program) => [program, ...POWERSHELL_ARGS, script]);\n\t\t\treturn runCommand(commands, execution, args.timeout, api, context);\n\t\t},\n\t});\n}\n"]}
|
package/dist/tools/edit.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { type Static
|
|
1
|
+
import { type Static } from "@earendil-works/pi-schema";
|
|
2
2
|
import type { ToolRegistration } from "../harness/types.ts";
|
|
3
|
-
declare const editSchema:
|
|
4
|
-
path:
|
|
5
|
-
edits:
|
|
6
|
-
oldText:
|
|
7
|
-
newText:
|
|
8
|
-
}
|
|
3
|
+
declare const editSchema: import("@earendil-works/pi-schema").Schema<{
|
|
4
|
+
path: string;
|
|
5
|
+
edits: {
|
|
6
|
+
oldText: string;
|
|
7
|
+
newText: string;
|
|
8
|
+
}[];
|
|
9
9
|
}>;
|
|
10
10
|
export type EditToolInput = Static<typeof editSchema>;
|
|
11
11
|
export type EditToolDetails = {
|
package/dist/tools/edit.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,KAAK,MAAM,EAAO,MAAM,2BAA2B,CAAC;AAGvE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AA0B5D,QAAA,MAAM,UAAU;;;;;;EASf,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAsCtD,MAAM,MAAM,eAAe,GAAG;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAaF,wBAAgB,cAAc,IAAI,gBAAgB,CAAC,OAAO,UAAU,EAAE,eAAe,CAAC,CAsDrF"}
|
package/dist/tools/edit.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { arr, obj, str } from "@earendil-works/pi-schema";
|
|
2
2
|
import { defineTool } from "../harness/define.js";
|
|
3
3
|
import { applyEditsToNormalizedContent, detectLineEnding, generateDiffString, generateUnifiedPatch, normalizeToLF, restoreLineEndings, stripBom, } from "./edit-diff.js";
|
|
4
4
|
import { requireEnv } from "./env.js";
|
|
5
5
|
import { withFileMutationQueue } from "./file-mutation-queue.js";
|
|
6
6
|
import { resolveToolPath } from "./path-utils.js";
|
|
7
|
-
const replaceEditSchema =
|
|
8
|
-
oldText:
|
|
7
|
+
const replaceEditSchema = obj({
|
|
8
|
+
oldText: str({
|
|
9
9
|
description: "Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.",
|
|
10
10
|
}),
|
|
11
|
-
newText:
|
|
12
|
-
});
|
|
13
|
-
const editSchema =
|
|
14
|
-
path:
|
|
15
|
-
edits:
|
|
11
|
+
newText: str({ description: "Replacement text for this targeted edit." }),
|
|
12
|
+
}, { open: true });
|
|
13
|
+
const editSchema = obj({
|
|
14
|
+
path: str({ description: "Path to the file to edit (relative or absolute)" }),
|
|
15
|
+
edits: arr(replaceEditSchema, {
|
|
16
16
|
description: "One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.",
|
|
17
17
|
}),
|
|
18
|
-
});
|
|
18
|
+
}, { open: true });
|
|
19
19
|
function isSingleEditInput(value) {
|
|
20
20
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
21
21
|
return false;
|
package/dist/tools/edit.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ed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MAAM,WAAW,GAAG,MAAM,GAAG,CAAC,SAAS,CAAC,YAAY,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;gBAC7E,IAAI,CAAC,WAAW,CAAC,EAAE;oBAAE,MAAM,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC;gBACpE,IAAI,OAAO,CAAC,WAAW,EAAE,OAAO;oBAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;gBAEvE,MAAM,UAAU,GAAG,kBAAkB,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;gBAC/D,MAAM,OAAO,GAAoB;oBAChC,IAAI,EAAE,UAAU,CAAC,IAAI;oBACrB,KAAK,EAAE,oBAAoB,CAAC,IAAI,EAAE,WAAW,EAAE,UAAU,CAAC;oBAC1D,GAAG,CAAC,UAAU,CAAC,gBAAgB,KAAK,SAAS;wBAC5C,CAAC,CAAC,EAAE;wBACJ,CAAC,CAAC,EAAE,gBAAgB,EAAE,UAAU,CAAC,gBAAgB,EAAE,CAAC;iBACrD,CAAC;gBACF,OAAO;oBACN,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,yBAAyB,KAAK,CAAC,MAAM,gBAAgB,IAAI,GAAG,EAAE,CAAC;oBAC9F,OAAO;iBACP,CAAC;YACH,CAAC,EACD,OAAO,CACP,CAAC;QACH,CAAC;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { type Static, Type } from \"typebox\";\nimport type { FileError } from \"../env/index.ts\";\nimport { defineTool } from \"../harness/define.ts\";\nimport type { ToolRegistration } from \"../harness/types.ts\";\nimport {\n\tapplyEditsToNormalizedContent,\n\tdetectLineEnding,\n\ttype Edit,\n\tgenerateDiffString,\n\tgenerateUnifiedPatch,\n\tnormalizeToLF,\n\trestoreLineEndings,\n\tstripBom,\n} from \"./edit-diff.ts\";\nimport { requireEnv } from \"./env.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToolPath } from \"./path-utils.ts\";\n\nconst replaceEditSchema = Type.Object({\n\toldText: Type.String({\n\t\tdescription:\n\t\t\t\"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.\",\n\t}),\n\tnewText: Type.String({ description: \"Replacement text for this targeted edit.\" }),\n});\n\nconst editSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to edit (relative or absolute)\" }),\n\tedits: Type.Array(replaceEditSchema, {\n\t\tdescription:\n\t\t\t\"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.\",\n\t}),\n});\n\nexport type EditToolInput = Static<typeof editSchema>;\ntype LegacyEditToolInput = EditToolInput & { oldText?: unknown; newText?: unknown };\ntype SingleEditInput = { oldText: string; newText: string };\n\nfunction isSingleEditInput(value: unknown): value is SingleEditInput {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst edit = value as Record<string, unknown>;\n\treturn typeof edit.oldText === \"string\" && typeof edit.newText === \"string\";\n}\n\n/**\n * Repair shapes models commonly send: `edits` as a JSON string or as a single edit object, and a top-level\n * `oldText`/`newText` pair. Works on a copy; the call's arguments stay unchanged.\n */\nfunction prepareEditArguments(input: unknown): EditToolInput {\n\tif (!input || typeof input !== \"object\" || Array.isArray(input)) return input as EditToolInput;\n\tconst args: Record<string, unknown> = { ...input };\n\tif (typeof args.edits === \"string\") {\n\t\ttry {\n\t\t\tconst parsed: unknown = JSON.parse(args.edits);\n\t\t\tif (Array.isArray(parsed)) {\n\t\t\t\targs.edits = parsed;\n\t\t\t} else if (isSingleEditInput(parsed)) {\n\t\t\t\targs.edits = [parsed];\n\t\t\t}\n\t\t} catch {}\n\t} else if (isSingleEditInput(args.edits)) {\n\t\targs.edits = [args.edits];\n\t}\n\n\tconst legacy = args as LegacyEditToolInput;\n\tif (typeof legacy.oldText !== \"string\" || typeof legacy.newText !== \"string\") return legacy;\n\tconst edits = Array.isArray(legacy.edits) ? [...legacy.edits] : [];\n\tedits.push({ oldText: legacy.oldText, newText: legacy.newText });\n\tconst { oldText: _oldText, newText: _newText, ...rest } = legacy;\n\treturn { ...rest, edits };\n}\n\nexport type EditToolDetails = {\n\tdiff: string;\n\tpatch: string;\n\tfirstChangedLine?: number;\n};\n\nfunction validateEditInput(input: EditToolInput): { path: string; edits: Edit[] } {\n\tif (!Array.isArray(input.edits) || input.edits.length === 0) {\n\t\tthrow new Error(\"Edit tool input is invalid. edits must contain at least one replacement.\");\n\t}\n\treturn { path: input.path, edits: input.edits };\n}\n\nfunction editAccessError(path: string, error: FileError): Error {\n\treturn new Error(`Could not edit file: ${path}. Error code: ${error.code}.`, { cause: error });\n}\n\nexport function createEditTool(): ToolRegistration<typeof editSchema, EditToolDetails> {\n\treturn defineTool({\n\t\tname: \"edit\",\n\t\tdescription:\n\t\t\t\"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.\",\n\t\tparameters: editSchema,\n\t\tprepareArguments: prepareEditArguments,\n\t\tasync execute(args, api, context) {\n\t\t\tconst { path, edits } = validateEditInput(args);\n\t\t\tconst env = requireEnv(api);\n\t\t\tconst absolutePath = await resolveToolPath(env, path, context);\n\t\t\treturn withFileMutationQueue(\n\t\t\t\tenv,\n\t\t\t\tabsolutePath,\n\t\t\t\tasync () => {\n\t\t\t\t\tif (context.abortSignal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t\tconst info = await env.fileInfo(absolutePath, context);\n\t\t\t\t\tif (!info.ok) throw editAccessError(path, info.error);\n\t\t\t\t\tif (info.value.kind !== \"file\" && info.value.kind !== \"symlink\") {\n\t\t\t\t\t\tthrow new Error(`Could not edit file: ${path}. Path is not a file.`);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst readResult = await env.readTextFile(absolutePath, context);\n\t\t\t\t\tif (!readResult.ok) throw editAccessError(path, readResult.error);\n\t\t\t\t\tif (context.abortSignal?.aborted) throw new Error(\"Operation aborted\");\n\n\t\t\t\t\tconst { bom, text: content } = stripBom(readResult.value);\n\t\t\t\t\tconst originalEnding = detectLineEnding(content);\n\t\t\t\t\tconst normalizedContent = normalizeToLF(content);\n\t\t\t\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\t\t\t\t\tif (context.abortSignal?.aborted) throw new Error(\"Operation aborted\");\n\n\t\t\t\t\tconst finalContent = bom + restoreLineEndings(newContent, originalEnding);\n\t\t\t\t\tconst writeResult = await env.writeFile(absolutePath, finalContent, context);\n\t\t\t\t\tif (!writeResult.ok) throw editAccessError(path, writeResult.error);\n\t\t\t\t\tif (context.abortSignal?.aborted) throw new Error(\"Operation aborted\");\n\n\t\t\t\t\tconst diffResult = generateDiffString(baseContent, newContent);\n\t\t\t\t\tconst details: EditToolDetails = {\n\t\t\t\t\t\tdiff: diffResult.diff,\n\t\t\t\t\t\tpatch: generateUnifiedPatch(path, baseContent, newContent),\n\t\t\t\t\t\t...(diffResult.firstChangedLine === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { firstChangedLine: diffResult.firstChangedLine }),\n\t\t\t\t\t};\n\t\t\t\t\treturn {\n\t\t\t\t\t\toutput: [{ type: \"text\", text: `Successfully replaced ${edits.length} block(s) in ${path}.` }],\n\t\t\t\t\t\tdetails,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tcontext,\n\t\t\t);\n\t\t},\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"edit.js","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAe,GAAG,EAAE,MAAM,2BAA2B,CAAC;AAEvE,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EACN,6BAA6B,EAC7B,gBAAgB,EAEhB,kBAAkB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AAO,CAAC,WAAW,EAAE,OAAO;oBAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;gBAEvE,MAAM,UAAU,GAAG,kBAAkB,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;gBAC/D,MAAM,OAAO,GAAoB;oBAChC,IAAI,EAAE,UAAU,CAAC,IAAI;oBACrB,KAAK,EAAE,oBAAoB,CAAC,IAAI,EAAE,WAAW,EAAE,UAAU,CAAC;oBAC1D,GAAG,CAAC,UAAU,CAAC,gBAAgB,KAAK,SAAS;wBAC5C,CAAC,CAAC,EAAE;wBACJ,CAAC,CAAC,EAAE,gBAAgB,EAAE,UAAU,CAAC,gBAAgB,EAAE,CAAC;iBACrD,CAAC;gBACF,OAAO;oBACN,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,yBAAyB,KAAK,CAAC,MAAM,gBAAgB,IAAI,GAAG,EAAE,CAAC;oBAC9F,OAAO;iBACP,CAAC;YACH,CAAC,EACD,OAAO,CACP,CAAC;QACH,CAAC;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { arr, obj, type Static, str } from \"@earendil-works/pi-schema\";\nimport type { FileError } from \"../env/index.ts\";\nimport { defineTool } from \"../harness/define.ts\";\nimport type { ToolRegistration } from \"../harness/types.ts\";\nimport {\n\tapplyEditsToNormalizedContent,\n\tdetectLineEnding,\n\ttype Edit,\n\tgenerateDiffString,\n\tgenerateUnifiedPatch,\n\tnormalizeToLF,\n\trestoreLineEndings,\n\tstripBom,\n} from \"./edit-diff.ts\";\nimport { requireEnv } from \"./env.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToolPath } from \"./path-utils.ts\";\n\nconst replaceEditSchema = obj(\n\t{\n\t\toldText: str({\n\t\t\tdescription:\n\t\t\t\t\"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.\",\n\t\t}),\n\t\tnewText: str({ description: \"Replacement text for this targeted edit.\" }),\n\t},\n\t{ open: true },\n);\n\nconst editSchema = obj(\n\t{\n\t\tpath: str({ description: \"Path to the file to edit (relative or absolute)\" }),\n\t\tedits: arr(replaceEditSchema, {\n\t\t\tdescription:\n\t\t\t\t\"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.\",\n\t\t}),\n\t},\n\t{ open: true },\n);\n\nexport type EditToolInput = Static<typeof editSchema>;\ntype LegacyEditToolInput = EditToolInput & { oldText?: unknown; newText?: unknown };\ntype SingleEditInput = { oldText: string; newText: string };\n\nfunction isSingleEditInput(value: unknown): value is SingleEditInput {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst edit = value as Record<string, unknown>;\n\treturn typeof edit.oldText === \"string\" && typeof edit.newText === \"string\";\n}\n\n/**\n * Repair shapes models commonly send: `edits` as a JSON string or as a single edit object, and a top-level\n * `oldText`/`newText` pair. Works on a copy; the call's arguments stay unchanged.\n */\nfunction prepareEditArguments(input: unknown): EditToolInput {\n\tif (!input || typeof input !== \"object\" || Array.isArray(input)) return input as EditToolInput;\n\tconst args: Record<string, unknown> = { ...input };\n\tif (typeof args.edits === \"string\") {\n\t\ttry {\n\t\t\tconst parsed: unknown = JSON.parse(args.edits);\n\t\t\tif (Array.isArray(parsed)) {\n\t\t\t\targs.edits = parsed;\n\t\t\t} else if (isSingleEditInput(parsed)) {\n\t\t\t\targs.edits = [parsed];\n\t\t\t}\n\t\t} catch {}\n\t} else if (isSingleEditInput(args.edits)) {\n\t\targs.edits = [args.edits];\n\t}\n\n\tconst legacy = args as LegacyEditToolInput;\n\tif (typeof legacy.oldText !== \"string\" || typeof legacy.newText !== \"string\") return legacy;\n\tconst edits = Array.isArray(legacy.edits) ? [...legacy.edits] : [];\n\tedits.push({ oldText: legacy.oldText, newText: legacy.newText });\n\tconst { oldText: _oldText, newText: _newText, ...rest } = legacy;\n\treturn { ...rest, edits };\n}\n\nexport type EditToolDetails = {\n\tdiff: string;\n\tpatch: string;\n\tfirstChangedLine?: number;\n};\n\nfunction validateEditInput(input: EditToolInput): { path: string; edits: Edit[] } {\n\tif (!Array.isArray(input.edits) || input.edits.length === 0) {\n\t\tthrow new Error(\"Edit tool input is invalid. edits must contain at least one replacement.\");\n\t}\n\treturn { path: input.path, edits: input.edits };\n}\n\nfunction editAccessError(path: string, error: FileError): Error {\n\treturn new Error(`Could not edit file: ${path}. Error code: ${error.code}.`, { cause: error });\n}\n\nexport function createEditTool(): ToolRegistration<typeof editSchema, EditToolDetails> {\n\treturn defineTool({\n\t\tname: \"edit\",\n\t\tdescription:\n\t\t\t\"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.\",\n\t\tparameters: editSchema,\n\t\tprepareArguments: prepareEditArguments,\n\t\tasync execute(args, api, context) {\n\t\t\tconst { path, edits } = validateEditInput(args);\n\t\t\tconst env = requireEnv(api);\n\t\t\tconst absolutePath = await resolveToolPath(env, path, context);\n\t\t\treturn withFileMutationQueue(\n\t\t\t\tenv,\n\t\t\t\tabsolutePath,\n\t\t\t\tasync () => {\n\t\t\t\t\tif (context.abortSignal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t\tconst info = await env.fileInfo(absolutePath, context);\n\t\t\t\t\tif (!info.ok) throw editAccessError(path, info.error);\n\t\t\t\t\tif (info.value.kind !== \"file\" && info.value.kind !== \"symlink\") {\n\t\t\t\t\t\tthrow new Error(`Could not edit file: ${path}. Path is not a file.`);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst readResult = await env.readTextFile(absolutePath, context);\n\t\t\t\t\tif (!readResult.ok) throw editAccessError(path, readResult.error);\n\t\t\t\t\tif (context.abortSignal?.aborted) throw new Error(\"Operation aborted\");\n\n\t\t\t\t\tconst { bom, text: content } = stripBom(readResult.value);\n\t\t\t\t\tconst originalEnding = detectLineEnding(content);\n\t\t\t\t\tconst normalizedContent = normalizeToLF(content);\n\t\t\t\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\t\t\t\t\tif (context.abortSignal?.aborted) throw new Error(\"Operation aborted\");\n\n\t\t\t\t\tconst finalContent = bom + restoreLineEndings(newContent, originalEnding);\n\t\t\t\t\tconst writeResult = await env.writeFile(absolutePath, finalContent, context);\n\t\t\t\t\tif (!writeResult.ok) throw editAccessError(path, writeResult.error);\n\t\t\t\t\tif (context.abortSignal?.aborted) throw new Error(\"Operation aborted\");\n\n\t\t\t\t\tconst diffResult = generateDiffString(baseContent, newContent);\n\t\t\t\t\tconst details: EditToolDetails = {\n\t\t\t\t\t\tdiff: diffResult.diff,\n\t\t\t\t\t\tpatch: generateUnifiedPatch(path, baseContent, newContent),\n\t\t\t\t\t\t...(diffResult.firstChangedLine === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { firstChangedLine: diffResult.firstChangedLine }),\n\t\t\t\t\t};\n\t\t\t\t\treturn {\n\t\t\t\t\t\toutput: [{ type: \"text\", text: `Successfully replaced ${edits.length} block(s) in ${path}.` }],\n\t\t\t\t\t\tdetails,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tcontext,\n\t\t\t);\n\t\t},\n\t});\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Context } from "@earendil-works/chord";
|
|
1
|
+
import type { Context } from "@earendil-works/chord/context";
|
|
2
2
|
import { type ExecutionEnv } from "../env/index.ts";
|
|
3
3
|
/**
|
|
4
4
|
* Serialize `edit` and `write` mutations of one file within this process: same file system id and canonical path,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-mutation-queue.d.ts","sourceRoot":"","sources":["../../src/tools/file-mutation-queue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"file-mutation-queue.d.ts","sourceRoot":"","sources":["../../src/tools/file-mutation-queue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAC7D,OAAO,EAAE,KAAK,YAAY,EAAc,MAAM,iBAAiB,CAAC;AA0BhE;;;;GAIG;AACH,wBAAsB,qBAAqB,CAAC,CAAC,EAC5C,GAAG,EAAE,YAAY,EACjB,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACpB,OAAO,EAAE,OAAO,GACd,OAAO,CAAC,CAAC,CAAC,CAiBZ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-mutation-queue.js","sourceRoot":"","sources":["../../src/tools/file-mutation-queue.ts"],"names":[],"mappings":"AACA,OAAO,EAAqB,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAEhE,2FAA2F;AAC3F,MAAM,MAAM,GAAG,IAAI,GAAG,EAAyB,CAAC;AAEhD,KAAK,UAAU,WAAW,CAAC,GAAiB,EAAE,IAAY,EAAE,OAAgB;IAC3E,MAAM,YAAY,GAAG,UAAU,CAAC,MAAM,GAAG,CAAC,YAAY,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;IACvE,OAAO,GAAG,GAAG,CAAC,EAAE,KAAK,MAAM,SAAS,CAAC,GAAG,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,CAAC;AACpE,CAAC;AAED;;;GAGG;AACH,KAAK,UAAU,SAAS,CAAC,GAAiB,EAAE,YAAoB,EAAE,OAAgB;IACjF,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,aAAa,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;IAC9D,IAAI,MAAM,CAAC,EAAE;QAAE,OAAO,MAAM,CAAC,KAAK,CAAC;IACnC,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,eAAe;QAAE,OAAO,YAAY,CAAC;IAC/D,IAAI,MAAM,CAAC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AAC;IACvC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IACtB,MAAM,QAAQ,CAAC;IACf,IAAI,CAAC;QACJ,OAAO,MAAM,EAAE,EAAE,CAAC;IACnB,CAAC;YAAS,CAAC;QACV,OAAO,EAAE,CAAC;QACV,IAAI,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,IAAI;YAAE,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAClD,CAAC;AACF,CAAC","sourcesContent":["import type { Context } from \"@earendil-works/chord\";\nimport { type ExecutionEnv, getOrThrow } from \"../env/index.ts\";\n\n/** Tail of the mutation chain of each file, keyed by file system id and canonical path. */\nconst queues = new Map<string, Promise<void>>();\n\nasync function mutationKey(env: ExecutionEnv, path: string, context: Context): Promise<string> {\n\tconst absolutePath = getOrThrow(await env.absolutePath(path, context));\n\treturn `${env.id}\\0${await canonical(env, absolutePath, context)}`;\n}\n\n/**\n * The canonical path; for a file that does not exist yet, its canonical parent joined with its name, so a `write` that\n * creates a file and a later mutation of it share one key even under a symlinked directory.\n */\nasync function canonical(env: ExecutionEnv, absolutePath: string, context: Context): Promise<string> {\n\tconst result = await env.canonicalPath(absolutePath, context);\n\tif (result.ok) return result.value;\n\tif (result.error.code === \"not_supported\") return absolutePath;\n\tif (result.error.code !== \"not_found\") throw result.error;\n\t// The file system splits the path, so a name may contain characters that are separators elsewhere.\n\tconst parent = getOrThrow(await env.joinPath([absolutePath, \"..\"], context));\n\tif (parent === absolutePath || !absolutePath.startsWith(parent)) return absolutePath;\n\tconst name = absolutePath.slice(parent.length + (/[/\\\\]$/.test(parent) ? 0 : 1));\n\treturn getOrThrow(await env.joinPath([await canonical(env, parent, context), name], context));\n}\n\n/**\n * Serialize `edit` and `write` mutations of one file within this process: same file system id and canonical path,\n * whichever environment object the call got. Other files, and other file systems, never wait. Concurrent calls on one\n * file run in the order their keys resolve. Not a lock against `bash` or other processes.\n */\nexport async function withFileMutationQueue<T>(\n\tenv: ExecutionEnv,\n\tpath: string,\n\tfn: () => Promise<T>,\n\tcontext: Context,\n): Promise<T> {\n\tconst key = await mutationKey(env, path, context);\n\t// Take the slot without awaiting, so no other call can take it in between.\n\tconst previous = queues.get(key) ?? Promise.resolve();\n\tlet release = (): void => {};\n\tconst done = new Promise<void>((resolve) => {\n\t\trelease = resolve;\n\t});\n\tconst tail = previous.then(() => done);\n\tqueues.set(key, tail);\n\tawait previous;\n\ttry {\n\t\treturn await fn();\n\t} finally {\n\t\trelease();\n\t\tif (queues.get(key) === tail) queues.delete(key);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"file-mutation-queue.js","sourceRoot":"","sources":["../../src/tools/file-mutation-queue.ts"],"names":[],"mappings":"AACA,OAAO,EAAqB,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAEhE,2FAA2F;AAC3F,MAAM,MAAM,GAAG,IAAI,GAAG,EAAyB,CAAC;AAEhD,KAAK,UAAU,WAAW,CAAC,GAAiB,EAAE,IAAY,EAAE,OAAgB;IAC3E,MAAM,YAAY,GAAG,UAAU,CAAC,MAAM,GAAG,CAAC,YAAY,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;IACvE,OAAO,GAAG,GAAG,CAAC,EAAE,KAAK,MAAM,SAAS,CAAC,GAAG,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,CAAC;AACpE,CAAC;AAED;;;GAGG;AACH,KAAK,UAAU,SAAS,CAAC,GAAiB,EAAE,YAAoB,EAAE,OAAgB;IACjF,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,aAAa,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;IAC9D,IAAI,MAAM,CAAC,EAAE;QAAE,OAAO,MAAM,CAAC,KAAK,CAAC;IACnC,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,eAAe;QAAE,OAAO,YAAY,CAAC;IAC/D,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,WAAW;QA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,GAAG,EAAE,IAAI,CAAC,CAAC;IACtB,MAAM,QAAQ,CAAC;IACf,IAAI,CAAC;QACJ,OAAO,MAAM,EAAE,EAAE,CAAC;IACnB,CAAC;YAAS,CAAC;QACV,OAAO,EAAE,CAAC;QACV,IAAI,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,IAAI;YAAE,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAClD,CAAC;AACF,CAAC","sourcesContent":["import type { Context } from \"@earendil-works/chord/context\";\nimport { type ExecutionEnv, getOrThrow } from \"../env/index.ts\";\n\n/** Tail of the mutation chain of each file, keyed by file system id and canonical path. */\nconst queues = new Map<string, Promise<void>>();\n\nasync function mutationKey(env: ExecutionEnv, path: string, context: Context): Promise<string> {\n\tconst absolutePath = getOrThrow(await env.absolutePath(path, context));\n\treturn `${env.id}\\0${await canonical(env, absolutePath, context)}`;\n}\n\n/**\n * The canonical path; for a file that does not exist yet, its canonical parent joined with its name, so a `write` that\n * creates a file and a later mutation of it share one key even under a symlinked directory.\n */\nasync function canonical(env: ExecutionEnv, absolutePath: string, context: Context): Promise<string> {\n\tconst result = await env.canonicalPath(absolutePath, context);\n\tif (result.ok) return result.value;\n\tif (result.error.code === \"not_supported\") return absolutePath;\n\tif (result.error.code !== \"not_found\") throw result.error;\n\t// The file system splits the path, so a name may contain characters that are separators elsewhere.\n\tconst parent = getOrThrow(await env.joinPath([absolutePath, \"..\"], context));\n\tif (parent === absolutePath || !absolutePath.startsWith(parent)) return absolutePath;\n\tconst name = absolutePath.slice(parent.length + (/[/\\\\]$/.test(parent) ? 0 : 1));\n\treturn getOrThrow(await env.joinPath([await canonical(env, parent, context), name], context));\n}\n\n/**\n * Serialize `edit` and `write` mutations of one file within this process: same file system id and canonical path,\n * whichever environment object the call got. Other files, and other file systems, never wait. Concurrent calls on one\n * file run in the order their keys resolve. Not a lock against `bash` or other processes.\n */\nexport async function withFileMutationQueue<T>(\n\tenv: ExecutionEnv,\n\tpath: string,\n\tfn: () => Promise<T>,\n\tcontext: Context,\n): Promise<T> {\n\tconst key = await mutationKey(env, path, context);\n\t// Take the slot without awaiting, so no other call can take it in between.\n\tconst previous = queues.get(key) ?? Promise.resolve();\n\tlet release = (): void => {};\n\tconst done = new Promise<void>((resolve) => {\n\t\trelease = resolve;\n\t});\n\tconst tail = previous.then(() => done);\n\tqueues.set(key, tail);\n\tawait previous;\n\ttry {\n\t\treturn await fn();\n\t} finally {\n\t\trelease();\n\t\tif (queues.get(key) === tail) queues.delete(key);\n\t}\n}\n"]}
|
package/dist/tools/index.d.ts
CHANGED
|
@@ -8,39 +8,39 @@ export { createWriteTool, type WriteToolInput } from "./write.ts";
|
|
|
8
8
|
* The `coding-tools` extension: `read`, `write`, `edit`, and `bash`; nothing installs it automatically.
|
|
9
9
|
* `createPowerShellTool()` adds `powershell`. `images` prepares the images `read` returns (see `ReadToolOptions`).
|
|
10
10
|
*/
|
|
11
|
-
export declare function createCodingTools(options?: ReadToolOptions): import("../index.ts").Extension<import("../index.ts").ToolRegistration<import("
|
|
12
|
-
command:
|
|
13
|
-
timeout
|
|
14
|
-
}>> | import("../index.ts").ToolRegistration<import("
|
|
15
|
-
path:
|
|
16
|
-
content:
|
|
17
|
-
}>> | import("../index.ts").ToolRegistration<import("
|
|
18
|
-
path:
|
|
19
|
-
edits:
|
|
20
|
-
oldText:
|
|
21
|
-
newText:
|
|
22
|
-
}
|
|
23
|
-
}>, import("./edit.ts").EditToolDetails> | import("../index.ts").ToolRegistration<import("
|
|
24
|
-
path:
|
|
25
|
-
offset
|
|
26
|
-
limit
|
|
11
|
+
export declare function createCodingTools(options?: ReadToolOptions): import("../index.ts").Extension<import("../index.ts").ToolRegistration<import("@earendil-works/pi-schema").Schema<{
|
|
12
|
+
command: string;
|
|
13
|
+
timeout?: number | undefined;
|
|
14
|
+
}>> | import("../index.ts").ToolRegistration<import("@earendil-works/pi-schema").Schema<{
|
|
15
|
+
path: string;
|
|
16
|
+
content: string;
|
|
17
|
+
}>> | import("../index.ts").ToolRegistration<import("@earendil-works/pi-schema").Schema<{
|
|
18
|
+
path: string;
|
|
19
|
+
edits: {
|
|
20
|
+
oldText: string;
|
|
21
|
+
newText: string;
|
|
22
|
+
}[];
|
|
23
|
+
}>, import("./edit.ts").EditToolDetails> | import("../index.ts").ToolRegistration<import("@earendil-works/pi-schema").Schema<{
|
|
24
|
+
path: string;
|
|
25
|
+
offset?: number | undefined;
|
|
26
|
+
limit?: number | undefined;
|
|
27
27
|
}>, import("./read.ts").ReadToolDetails>>;
|
|
28
28
|
/** `createCodingTools()` without an image processor. */
|
|
29
|
-
export declare const CodingTools: import("../index.ts").Extension<import("../index.ts").ToolRegistration<import("
|
|
30
|
-
command:
|
|
31
|
-
timeout
|
|
32
|
-
}>> | import("../index.ts").ToolRegistration<import("
|
|
33
|
-
path:
|
|
34
|
-
content:
|
|
35
|
-
}>> | import("../index.ts").ToolRegistration<import("
|
|
36
|
-
path:
|
|
37
|
-
edits:
|
|
38
|
-
oldText:
|
|
39
|
-
newText:
|
|
40
|
-
}
|
|
41
|
-
}>, import("./edit.ts").EditToolDetails> | import("../index.ts").ToolRegistration<import("
|
|
42
|
-
path:
|
|
43
|
-
offset
|
|
44
|
-
limit
|
|
29
|
+
export declare const CodingTools: import("../index.ts").Extension<import("../index.ts").ToolRegistration<import("@earendil-works/pi-schema").Schema<{
|
|
30
|
+
command: string;
|
|
31
|
+
timeout?: number | undefined;
|
|
32
|
+
}>> | import("../index.ts").ToolRegistration<import("@earendil-works/pi-schema").Schema<{
|
|
33
|
+
path: string;
|
|
34
|
+
content: string;
|
|
35
|
+
}>> | import("../index.ts").ToolRegistration<import("@earendil-works/pi-schema").Schema<{
|
|
36
|
+
path: string;
|
|
37
|
+
edits: {
|
|
38
|
+
oldText: string;
|
|
39
|
+
newText: string;
|
|
40
|
+
}[];
|
|
41
|
+
}>, import("./edit.ts").EditToolDetails> | import("../index.ts").ToolRegistration<import("@earendil-works/pi-schema").Schema<{
|
|
42
|
+
path: string;
|
|
43
|
+
offset?: number | undefined;
|
|
44
|
+
limit?: number | undefined;
|
|
45
45
|
}>, import("./read.ts").ReadToolDetails>>;
|
|
46
46
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Context } from "@earendil-works/chord";
|
|
1
|
+
import type { Context } from "@earendil-works/chord/context";
|
|
2
2
|
import { type ExecutionEnv } from "../env/index.ts";
|
|
3
3
|
export declare function resolveToolPath(env: ExecutionEnv, path: string, context: Context): Promise<string>;
|
|
4
4
|
export declare function resolveReadToolPath(env: ExecutionEnv, path: string, context: Context): Promise<string>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path-utils.d.ts","sourceRoot":"","sources":["../../src/tools/path-utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"path-utils.d.ts","sourceRoot":"","sources":["../../src/tools/path-utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAC7D,OAAO,EAAE,KAAK,YAAY,EAAc,MAAM,iBAAiB,CAAC;AAUhE,wBAAsB,eAAe,CAAC,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,CAExG;AAED,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,CAc5G"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path-utils.js","sourceRoot":"","sources":["../../src/tools/path-utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAqB,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,cAAc,GAAG,0CAA0C,CAAC;AAClE,MAAM,qBAAqB,GAAG,QAA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.ts\";\n\nconst UNICODE_SPACES = /[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g;\nconst NARROW_NO_BREAK_SPACE = \"\\u202F\";\n\nfunction normalizeToolPath(path: string): string {\n\tconst normalized = path.replace(UNICODE_SPACES, \" \");\n\treturn normalized.startsWith(\"@\") ? normalized.slice(1) : normalized;\n}\n\nexport async function resolveToolPath(env: ExecutionEnv, path: string, context: Context): Promise<string> {\n\treturn getOrThrow(await env.absolutePath(normalizeToolPath(path), context));\n}\n\nexport async function resolveReadToolPath(env: ExecutionEnv, path: string, context: Context): Promise<string> {\n\tconst resolved = await resolveToolPath(env, path, context);\n\tconst variants = [\n\t\tresolved,\n\t\tresolved.replace(/ (AM|PM)\\./gi, `${NARROW_NO_BREAK_SPACE}$1.`),\n\t\tresolved.normalize(\"NFD\"),\n\t\tresolved.replace(/'/g, \"\\u2019\"),\n\t\tresolved.normalize(\"NFD\").replace(/'/g, \"\\u2019\"),\n\t];\n\n\tfor (const variant of new Set(variants)) {\n\t\tif (getOrThrow(await env.exists(variant, context))) return variant;\n\t}\n\treturn resolved;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"path-utils.js","sourceRoot":"","sources":["../../src/tools/path-utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAqB,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,cAAc,GAAG,0CAA0C,CAAC;AAClE,MAAM,qBAAqB,GAAG,QAAQ,CAAC;AAEvC,SAAS,iBAAiB,CAAC,IAAY;IACtC,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE,GAAG,CAAC,CAAC;IACrD,OAAO,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC;AACtE,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,GAAiB,EAAE,IAAY,EAAE,OAAgB;IACtF,OAAO,UAAU,CAAC,MAAM,GAAG,CAAC,YAAY,CAAC,iBAAiB,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;AAC7E,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,mBAAmB,CAAC,GAAiB,EAAE,IAAY,EAAE,OAAgB;IAC1F,MAAM,QAAQ,GAAG,MAAM,eAAe,CAAC,GAAG,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;IAC3D,MAAM,QAAQ,GAAG;QAChB,QAAQ;QACR,QAAQ,CAAC,OAAO,CAAC,cAAc,EAAE,GAAG,qBAAqB,KAAK,CAAC;QAC/D,QAAQ,CAAC,SAAS,CAAC,KAAK,CAAC;QACzB,QAAQ,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC;QAChC,QAAQ,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC;KACjD,CAAC;IAEF,KAAK,MAAM,OAAO,IAAI,IAAI,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;QACzC,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAAE,OAAO,OAAO,CAAC;IACpE,CAAC;IACD,OAAO,QAAQ,CAAC;AACjB,CAAC","sourcesContent":["import type { Context } from \"@earendil-works/chord/context\";\nimport { type ExecutionEnv, getOrThrow } from \"../env/index.ts\";\n\nconst UNICODE_SPACES = /[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g;\nconst NARROW_NO_BREAK_SPACE = \"\\u202F\";\n\nfunction normalizeToolPath(path: string): string {\n\tconst normalized = path.replace(UNICODE_SPACES, \" \");\n\treturn normalized.startsWith(\"@\") ? normalized.slice(1) : normalized;\n}\n\nexport async function resolveToolPath(env: ExecutionEnv, path: string, context: Context): Promise<string> {\n\treturn getOrThrow(await env.absolutePath(normalizeToolPath(path), context));\n}\n\nexport async function resolveReadToolPath(env: ExecutionEnv, path: string, context: Context): Promise<string> {\n\tconst resolved = await resolveToolPath(env, path, context);\n\tconst variants = [\n\t\tresolved,\n\t\tresolved.replace(/ (AM|PM)\\./gi, `${NARROW_NO_BREAK_SPACE}$1.`),\n\t\tresolved.normalize(\"NFD\"),\n\t\tresolved.replace(/'/g, \"\\u2019\"),\n\t\tresolved.normalize(\"NFD\").replace(/'/g, \"\\u2019\"),\n\t];\n\n\tfor (const variant of new Set(variants)) {\n\t\tif (getOrThrow(await env.exists(variant, context))) return variant;\n\t}\n\treturn resolved;\n}\n"]}
|