@earendil-works/pi-durable 1.1.0 → 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/CHANGELOG.md +40 -0
- package/README.md +147 -11
- package/dist/codemode/codemode.d.ts +173 -0
- package/dist/codemode/codemode.d.ts.map +1 -0
- package/dist/codemode/codemode.js +886 -0
- package/dist/codemode/codemode.js.map +1 -0
- package/dist/codemode/describe.d.ts +38 -0
- package/dist/codemode/describe.d.ts.map +1 -0
- package/dist/codemode/describe.js +119 -0
- package/dist/codemode/describe.js.map +1 -0
- package/dist/codemode/index.d.ts +3 -0
- package/dist/codemode/index.d.ts.map +1 -0
- package/dist/codemode/index.js +3 -0
- package/dist/codemode/index.js.map +1 -0
- package/dist/codemode/models.d.ts +28 -0
- package/dist/codemode/models.d.ts.map +1 -0
- package/dist/codemode/models.js +231 -0
- package/dist/codemode/models.js.map +1 -0
- package/dist/codemode/output.d.ts +41 -0
- package/dist/codemode/output.d.ts.map +1 -0
- package/dist/codemode/output.js +167 -0
- package/dist/codemode/output.js.map +1 -0
- package/dist/env/index.d.ts +42 -0
- package/dist/env/index.d.ts.map +1 -1
- package/dist/env/index.js.map +1 -1
- package/dist/errors.d.ts +20 -3
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +34 -5
- package/dist/errors.js.map +1 -1
- package/dist/harness/agent.d.ts +5 -2
- package/dist/harness/agent.d.ts.map +1 -1
- package/dist/harness/agent.js +69 -25
- package/dist/harness/agent.js.map +1 -1
- package/dist/harness/compaction.d.ts +6 -1
- package/dist/harness/compaction.d.ts.map +1 -1
- package/dist/harness/compaction.js +10 -7
- package/dist/harness/compaction.js.map +1 -1
- package/dist/harness/events.d.ts +35 -15
- package/dist/harness/events.d.ts.map +1 -1
- package/dist/harness/events.js +77 -23
- package/dist/harness/events.js.map +1 -1
- package/dist/harness/generation.d.ts +2 -0
- package/dist/harness/generation.d.ts.map +1 -1
- package/dist/harness/generation.js +31 -8
- package/dist/harness/generation.js.map +1 -1
- package/dist/harness/harness.d.ts +7 -0
- package/dist/harness/harness.d.ts.map +1 -1
- package/dist/harness/harness.js +53 -26
- package/dist/harness/harness.js.map +1 -1
- package/dist/harness/inbox.d.ts +16 -4
- package/dist/harness/inbox.d.ts.map +1 -1
- package/dist/harness/inbox.js +26 -3
- package/dist/harness/inbox.js.map +1 -1
- package/dist/harness/live.d.ts +74 -17
- package/dist/harness/live.d.ts.map +1 -1
- package/dist/harness/live.js +66 -14
- package/dist/harness/live.js.map +1 -1
- package/dist/harness/scheduler.d.ts +18 -5
- package/dist/harness/scheduler.d.ts.map +1 -1
- package/dist/harness/scheduler.js +696 -163
- package/dist/harness/scheduler.js.map +1 -1
- package/dist/harness/submissions.d.ts +7 -4
- package/dist/harness/submissions.d.ts.map +1 -1
- package/dist/harness/submissions.js +32 -13
- package/dist/harness/submissions.js.map +1 -1
- package/dist/harness/task-graph.d.ts +1 -1
- package/dist/harness/task-graph.d.ts.map +1 -1
- package/dist/harness/task-graph.js +15 -10
- package/dist/harness/task-graph.js.map +1 -1
- package/dist/harness/tool.d.ts +45 -5
- package/dist/harness/tool.d.ts.map +1 -1
- package/dist/harness/tool.js +377 -62
- package/dist/harness/tool.js.map +1 -1
- package/dist/harness/types.d.ts +153 -13
- package/dist/harness/types.d.ts.map +1 -1
- package/dist/harness/types.js.map +1 -1
- package/dist/harness/util.d.ts +6 -1
- package/dist/harness/util.d.ts.map +1 -1
- package/dist/harness/util.js +5 -2
- package/dist/harness/util.js.map +1 -1
- package/dist/harness/view.d.ts +6 -2
- package/dist/harness/view.d.ts.map +1 -1
- package/dist/harness/view.js +22 -12
- package/dist/harness/view.js.map +1 -1
- package/dist/images/cloudflare.d.ts +4 -0
- package/dist/images/cloudflare.d.ts.map +1 -0
- package/dist/images/cloudflare.js +9 -0
- package/dist/images/cloudflare.js.map +1 -0
- package/dist/images/exif.d.ts +3 -0
- package/dist/images/exif.d.ts.map +1 -0
- package/dist/images/exif.js +71 -0
- package/dist/images/exif.js.map +1 -0
- package/dist/images/index.d.ts +18 -0
- package/dist/images/index.d.ts.map +1 -0
- package/dist/images/index.js +125 -0
- package/dist/images/index.js.map +1 -0
- package/dist/images/node-worker.d.ts +17 -0
- package/dist/images/node-worker.d.ts.map +1 -0
- package/dist/images/node-worker.js +16 -0
- package/dist/images/node-worker.js.map +1 -0
- package/dist/images/node.d.ts +21 -0
- package/dist/images/node.d.ts.map +1 -0
- package/dist/images/node.js +121 -0
- package/dist/images/node.js.map +1 -0
- package/dist/index.d.ts +6 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/search.d.ts +13 -0
- package/dist/search.d.ts.map +1 -0
- package/dist/search.js +85 -0
- package/dist/search.js.map +1 -0
- package/dist/session/observation.d.ts +10 -3
- package/dist/session/observation.d.ts.map +1 -1
- package/dist/session/observation.js +24 -34
- package/dist/session/observation.js.map +1 -1
- package/dist/session/session.d.ts +68 -5
- package/dist/session/session.d.ts.map +1 -1
- package/dist/session/session.js +461 -49
- package/dist/session/session.js.map +1 -1
- package/dist/session/transaction.d.ts.map +1 -1
- package/dist/session/transaction.js +1 -0
- package/dist/session/transaction.js.map +1 -1
- package/dist/storage/jsonl/storage.d.ts +4 -0
- package/dist/storage/jsonl/storage.d.ts.map +1 -1
- package/dist/storage/jsonl/storage.js +2 -1
- package/dist/storage/jsonl/storage.js.map +1 -1
- package/dist/storage/memory.d.ts.map +1 -1
- package/dist/storage/memory.js +8 -10
- package/dist/storage/memory.js.map +1 -1
- package/dist/storage/scan.d.ts.map +1 -1
- package/dist/storage/scan.js +5 -4
- package/dist/storage/scan.js.map +1 -1
- package/dist/storage/sqlite/storage.d.ts.map +1 -1
- package/dist/storage/sqlite/storage.js +10 -12
- package/dist/storage/sqlite/storage.js.map +1 -1
- package/dist/testing/env-conformance.d.ts.map +1 -1
- package/dist/testing/env-conformance.js +100 -0
- package/dist/testing/env-conformance.js.map +1 -1
- package/dist/testing/runner.d.ts +1 -1
- package/dist/testing/runner.d.ts.map +1 -1
- package/dist/testing/runner.js.map +1 -1
- package/dist/testing/storage-conformance.d.ts.map +1 -1
- package/dist/testing/storage-conformance.js +3 -2
- package/dist/testing/storage-conformance.js.map +1 -1
- package/dist/testing/types.d.ts +2 -0
- package/dist/testing/types.d.ts.map +1 -1
- package/dist/testing/types.js.map +1 -1
- package/dist/tool-search/index.d.ts +2 -0
- package/dist/tool-search/index.d.ts.map +1 -0
- package/dist/tool-search/index.js +2 -0
- package/dist/tool-search/index.js.map +1 -0
- package/dist/tool-search/tool-search.d.ts +23 -0
- package/dist/tool-search/tool-search.d.ts.map +1 -0
- package/dist/tool-search/tool-search.js +84 -0
- package/dist/tool-search/tool-search.js.map +1 -0
- package/dist/tools/bash.d.ts +10 -2
- package/dist/tools/bash.d.ts.map +1 -1
- package/dist/tools/bash.js +27 -9
- package/dist/tools/bash.js.map +1 -1
- package/dist/tools/edit.js +1 -1
- package/dist/tools/edit.js.map +1 -1
- package/dist/tools/image-processor.d.ts +47 -0
- package/dist/tools/image-processor.d.ts.map +1 -0
- package/dist/tools/image-processor.js +30 -0
- package/dist/tools/image-processor.js.map +1 -0
- package/dist/tools/image.d.ts +8 -0
- package/dist/tools/image.d.ts.map +1 -1
- package/dist/tools/image.js +47 -0
- package/dist/tools/image.js.map +1 -1
- package/dist/tools/index.d.ts +25 -2
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +13 -5
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/read.d.ts +10 -2
- package/dist/tools/read.d.ts.map +1 -1
- package/dist/tools/read.js +87 -28
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/write.js +1 -1
- package/dist/tools/write.js.map +1 -1
- package/dist/types.d.ts +59 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +43 -4
package/dist/testing/types.d.ts
CHANGED
|
@@ -27,6 +27,8 @@ export interface EnvConformanceOptions {
|
|
|
27
27
|
readonly shell?: readonly string[];
|
|
28
28
|
/** Whether the shell's `ln -s` creates symbolic links; default true. */
|
|
29
29
|
readonly symlinks?: boolean;
|
|
30
|
+
/** Whether the environment implements the optional `listFiles`, which the suite then checks; default false. */
|
|
31
|
+
readonly listFiles?: boolean;
|
|
30
32
|
}
|
|
31
33
|
export interface EnvConformanceCase {
|
|
32
34
|
readonly name: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/testing/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAE3C,MAAM,WAAW,4BAA4B;IAC5C,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3C,WAAW,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,GAAG,IAAI,CAAC;IACtD,SAAS,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,GAAG,IAAI,CAAC;IACpD,gBAAgB,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,GAAG,IAAI,CAAC;IAC3D,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACpD,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,OAAO,CAAC,EAAE,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7E;AAED,MAAM,MAAM,0BAA0B,GAAG,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAErG,MAAM,WAAW,yBAAyB;IACzC,QAAQ,CAAC,UAAU,EAAE,4BAA4B,CAAC;IAClD,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,IAAI,CAAC,CAAC;CACrB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/testing/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ExecutionEnv } from \"../env/index.ts\";\nimport type { Storage } from \"../types.ts\";\n\nexport interface StorageConformanceAssertions {\n\tok(value: unknown, message?: string): void;\n\tstrictEqual(actual: unknown, expected: unknown): void;\n\tdeepEqual(actual: unknown, expected: unknown): void;\n\tpartialDeepEqual(actual: unknown, expected: unknown): void;\n\tgreaterThan(actual: number, expected: number): void;\n\trejects(operation: Promise<unknown>, messageIncludes: string): Promise<void>;\n}\n\nexport type StorageConformanceProvider = (use: (storage: Storage) => Promise<void>) => Promise<void>;\n\nexport interface StorageConformanceOptions {\n\treadonly assertions: StorageConformanceAssertions;\n\treadonly withStorage: StorageConformanceProvider;\n}\n\nexport interface StorageConformanceCase {\n\treadonly name: string;\n\trun(): Promise<void>;\n}\n\nexport type EnvConformanceAssertions = StorageConformanceAssertions;\n\n/** Calls `use` once with an environment whose `cwd` is a fresh, empty, writable directory, then cleans up. */\nexport type EnvConformanceProvider = (use: (env: ExecutionEnv) => Promise<void>) => Promise<void>;\n\nexport interface EnvConformanceOptions {\n\treadonly assertions: EnvConformanceAssertions;\n\treadonly withEnv: EnvConformanceProvider;\n\t/** Program and flag that run a POSIX shell script from the next argument; default `[\"sh\", \"-c\"]`. */\n\treadonly shell?: readonly string[];\n\t/** Whether the shell's `ln -s` creates symbolic links; default true. */\n\treadonly symlinks?: boolean;\n}\n\nexport interface EnvConformanceCase {\n\treadonly name: string;\n\t/** Cases that wait for an environment's watch latency need longer than a test runner's default timeout. */\n\treadonly timeoutMs?: number;\n\trun(): Promise<void>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/testing/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ExecutionEnv } from \"../env/index.ts\";\nimport type { Storage } from \"../types.ts\";\n\nexport interface StorageConformanceAssertions {\n\tok(value: unknown, message?: string): void;\n\tstrictEqual(actual: unknown, expected: unknown): void;\n\tdeepEqual(actual: unknown, expected: unknown): void;\n\tpartialDeepEqual(actual: unknown, expected: unknown): void;\n\tgreaterThan(actual: number, expected: number): void;\n\trejects(operation: Promise<unknown>, messageIncludes: string): Promise<void>;\n}\n\nexport type StorageConformanceProvider = (use: (storage: Storage) => Promise<void>) => Promise<void>;\n\nexport interface StorageConformanceOptions {\n\treadonly assertions: StorageConformanceAssertions;\n\treadonly withStorage: StorageConformanceProvider;\n}\n\nexport interface StorageConformanceCase {\n\treadonly name: string;\n\trun(): Promise<void>;\n}\n\nexport type EnvConformanceAssertions = StorageConformanceAssertions;\n\n/** Calls `use` once with an environment whose `cwd` is a fresh, empty, writable directory, then cleans up. */\nexport type EnvConformanceProvider = (use: (env: ExecutionEnv) => Promise<void>) => Promise<void>;\n\nexport interface EnvConformanceOptions {\n\treadonly assertions: EnvConformanceAssertions;\n\treadonly withEnv: EnvConformanceProvider;\n\t/** Program and flag that run a POSIX shell script from the next argument; default `[\"sh\", \"-c\"]`. */\n\treadonly shell?: readonly string[];\n\t/** Whether the shell's `ln -s` creates symbolic links; default true. */\n\treadonly symlinks?: boolean;\n\t/** Whether the environment implements the optional `listFiles`, which the suite then checks; default false. */\n\treadonly listFiles?: boolean;\n}\n\nexport interface EnvConformanceCase {\n\treadonly name: string;\n\t/** Cases that wait for an environment's watch latency need longer than a test runner's default timeout. */\n\treadonly timeoutMs?: number;\n\trun(): Promise<void>;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/tool-search/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,yBAAyB,EACzB,oBAAoB,EACpB,yBAAyB,EACzB,qBAAqB,EACrB,KAAK,qBAAqB,GAC1B,MAAM,kBAAkB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/tool-search/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,yBAAyB,EACzB,oBAAoB,EACpB,yBAAyB,EACzB,qBAAqB,GAErB,MAAM,kBAAkB,CAAC","sourcesContent":["export {\n\tcreateToolSearchExtension,\n\tcreateToolSearchTool,\n\tDEFAULT_TOOL_SEARCH_LIMIT,\n\tTOOL_SEARCH_TOOL_NAME,\n\ttype ToolSearchToolDetails,\n} from \"./tool-search.ts\";\n"]}
|
|
@@ -0,0 +1,23 @@
|
|
|
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
|
+
import type { ToolRegistration } from "../harness/types.ts";
|
|
8
|
+
export declare const TOOL_SEARCH_TOOL_NAME = "tool_search";
|
|
9
|
+
export declare const DEFAULT_TOOL_SEARCH_LIMIT = 8;
|
|
10
|
+
/** `tool_search` result details: the tools it loaded. */
|
|
11
|
+
export type ToolSearchToolDetails = {
|
|
12
|
+
loaded: string[];
|
|
13
|
+
};
|
|
14
|
+
export declare function createToolSearchTool(): ToolRegistration<Type.TObject<{
|
|
15
|
+
query: Type.TString;
|
|
16
|
+
limit: Type.TOptional<Type.TNumber>;
|
|
17
|
+
}>, import("@earendil-works/chord").JsonValue>;
|
|
18
|
+
/** 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<Type.TObject<{
|
|
20
|
+
query: Type.TString;
|
|
21
|
+
limit: Type.TOptional<Type.TNumber>;
|
|
22
|
+
}>, import("@earendil-works/chord").JsonValue>>;
|
|
23
|
+
//# sourceMappingURL=tool-search.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-search.d.ts","sourceRoot":"","sources":["../../src/tool-search/tool-search.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAE7C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAG5D,eAAO,MAAM,qBAAqB,gBAAgB,CAAC;AACnD,eAAO,MAAM,yBAAyB,IAAI,CAAC;AAY3C,yDAAyD;AACzD,MAAM,MAAM,qBAAqB,GAAG;IAAE,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AA8BzD,wBAAgB,oBAAoB;;;+CAgCnC;AAED,wGAAwG;AACxG,wBAAgB,yBAAyB;;;gDAExC"}
|
|
@@ -0,0 +1,84 @@
|
|
|
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
|
+
import { defineExtension, defineTool } from "../harness/define.js";
|
|
8
|
+
import { rankDocuments } from "../search.js";
|
|
9
|
+
export const TOOL_SEARCH_TOOL_NAME = "tool_search";
|
|
10
|
+
export const DEFAULT_TOOL_SEARCH_LIMIT = 8;
|
|
11
|
+
/** Fixed, so it does not change while deferred tools are registered, for example as MCP servers connect. */
|
|
12
|
+
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 = Type.Object({
|
|
14
|
+
query: Type.String({ description: "Search query for deferred tools." }),
|
|
15
|
+
limit: Type.Optional(Type.Number({ description: `Maximum number of tools to return. Defaults to ${DEFAULT_TOOL_SEARCH_LIMIT}.` })),
|
|
16
|
+
});
|
|
17
|
+
function isObject(value) {
|
|
18
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
19
|
+
}
|
|
20
|
+
/** Schema descriptions and property names, recursively. */
|
|
21
|
+
function schemaText(schema, parts) {
|
|
22
|
+
if (!isObject(schema))
|
|
23
|
+
return;
|
|
24
|
+
if (typeof schema.description === "string")
|
|
25
|
+
parts.push(schema.description);
|
|
26
|
+
if (isObject(schema.properties)) {
|
|
27
|
+
for (const [name, property] of Object.entries(schema.properties)) {
|
|
28
|
+
parts.push(name);
|
|
29
|
+
schemaText(property, parts);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
schemaText(schema.items, parts);
|
|
33
|
+
for (const key of ["anyOf", "oneOf", "allOf"]) {
|
|
34
|
+
const variants = schema[key];
|
|
35
|
+
if (Array.isArray(variants))
|
|
36
|
+
for (const variant of variants)
|
|
37
|
+
schemaText(variant, parts);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Search text of a tool: its name, the name with `_` as spaces, its description, and its parameters' text. */
|
|
41
|
+
function searchText(tool) {
|
|
42
|
+
const parts = [tool.name, tool.name.replaceAll("_", " "), tool.description];
|
|
43
|
+
schemaText(tool.parameters, parts);
|
|
44
|
+
return parts.filter((part) => part.trim() !== "").join(" ");
|
|
45
|
+
}
|
|
46
|
+
export function createToolSearchTool() {
|
|
47
|
+
return defineTool({
|
|
48
|
+
name: TOOL_SEARCH_TOOL_NAME,
|
|
49
|
+
description: TOOL_SEARCH_DESCRIPTION,
|
|
50
|
+
parameters: toolSearchSchema,
|
|
51
|
+
// Searching changes what the model is offered; scripts have their own `searchTools()`.
|
|
52
|
+
callers: ["model"],
|
|
53
|
+
replay: "safe",
|
|
54
|
+
async execute({ query, limit }, api, context) {
|
|
55
|
+
if (query.trim() === "")
|
|
56
|
+
throw new Error("query must not be empty");
|
|
57
|
+
const max = limit ?? DEFAULT_TOOL_SEARCH_LIMIT;
|
|
58
|
+
if (!Number.isInteger(max) || max <= 0)
|
|
59
|
+
throw new Error("limit must be a positive integer");
|
|
60
|
+
const candidates = (await api.agent(context)).deferred;
|
|
61
|
+
const documents = candidates.map((tool) => ({ name: tool.name, text: searchText(tool) }));
|
|
62
|
+
const loaded = rankDocuments(query, documents, max);
|
|
63
|
+
const text = loaded.length === 0
|
|
64
|
+
? "No matching tools found."
|
|
65
|
+
: `Loaded ${loaded.length} tool${loaded.length === 1 ? "" : "s"}. They are available from your next call:\n${loaded
|
|
66
|
+
.map((name) => {
|
|
67
|
+
const description = candidates.find((tool) => tool.name === name)?.description ?? "";
|
|
68
|
+
return `- ${name}: ${description.trim().split(/\r?\n/)[0]}`;
|
|
69
|
+
})
|
|
70
|
+
.join("\n")}`;
|
|
71
|
+
const details = { loaded };
|
|
72
|
+
return {
|
|
73
|
+
output: [{ type: "text", text }],
|
|
74
|
+
details,
|
|
75
|
+
...(loaded.length === 0 ? {} : { control: { addTools: loaded } }),
|
|
76
|
+
};
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
/** The `tool_search` extension: install it and select it where the model should find deferred tools. */
|
|
81
|
+
export function createToolSearchExtension() {
|
|
82
|
+
return defineExtension({ name: "tool-search", tools: [createToolSearchTool()] });
|
|
83
|
+
}
|
|
84
|
+
//# sourceMappingURL=tool-search.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-search.js","sourceRoot":"","sources":["../../src/tool-search/tool-search.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAEnE,OAAO,EAAE,aAAa,E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CAAC,CAAC,CAAC,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 { Type } from \"@earendil-works/pi-ai\";\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 = Type.Object({\n\tquery: Type.String({ description: \"Search query for deferred tools.\" }),\n\tlimit: Type.Optional(\n\t\tType.Number({ description: `Maximum number of tools to return. Defaults to ${DEFAULT_TOOL_SEARCH_LIMIT}.` }),\n\t),\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/** Schema descriptions and property names, recursively. */\nfunction schemaText(schema: unknown, parts: string[]): void {\n\tif (!isObject(schema)) return;\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, parts);\n\t\t}\n\t}\n\tschemaText(schema.items, parts);\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, parts);\n\t}\n}\n\n/** Search text of a tool: its name, the name with `_` as spaces, its description, and its parameters' text. */\nfunction searchText(tool: ToolRegistration): string {\n\tconst parts = [tool.name, tool.name.replaceAll(\"_\", \" \"), tool.description];\n\tschemaText(tool.parameters, parts);\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
|
@@ -9,8 +9,16 @@ declare const powershellSchema: Type.TObject<{
|
|
|
9
9
|
command: Type.TString;
|
|
10
10
|
timeout: Type.TOptional<Type.TNumber>;
|
|
11
11
|
}>;
|
|
12
|
+
/** What a program that calls `bash` or `powershell` receives. */
|
|
13
|
+
declare const shellStructuredOutputSchema: Type.TObject<{
|
|
14
|
+
output: Type.TString;
|
|
15
|
+
truncated: Type.TBoolean;
|
|
16
|
+
fullOutputPath: Type.TOptional<Type.TString>;
|
|
17
|
+
exitCode: Type.TNumber;
|
|
18
|
+
}>;
|
|
12
19
|
export type BashToolInput = Static<typeof bashSchema>;
|
|
13
20
|
export type PowerShellToolInput = Static<typeof powershellSchema>;
|
|
21
|
+
export type ShellStructuredOutput = Static<typeof shellStructuredOutputSchema>;
|
|
14
22
|
/** A command about to run, which `prepare` may change: the script, its working directory and environment. */
|
|
15
23
|
export interface BashExecution {
|
|
16
24
|
command: string;
|
|
@@ -34,8 +42,8 @@ export interface PowerShellToolOptions {
|
|
|
34
42
|
* Runs a command through the environment's shell. Its output streams to `api.output()`, where the Harness keeps the
|
|
35
43
|
* tail within the default limits; the result content is that retained output. The retained window goes to the
|
|
36
44
|
* environment, which may omit output outside it and report how much it omitted, so dropped counts stay exact. Output
|
|
37
|
-
* beyond the limits is spilled to a file whose path is reported as a diagnostic. A nonzero exit
|
|
38
|
-
* makes an error result that still carries the output and diagnostics.
|
|
45
|
+
* beyond the limits is spilled to a file whose path is reported as a diagnostic. A nonzero exit is an error result with
|
|
46
|
+
* the exit code; a timeout throws, which makes an error result that still carries the output and diagnostics.
|
|
39
47
|
*/
|
|
40
48
|
export declare function createBashTool(options?: BashToolOptions): ToolRegistration<typeof bashSchema>;
|
|
41
49
|
/**
|
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,uBAAuB,CAAC;AACrD,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,KAAK,EAAE,gBAAgB,
|
|
1
|
+
{"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../src/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,KAAK,EAAE,gBAAgB,EAAuB,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAMnG,QAAA,MAAM,UAAU;;;EAGd,CAAC;AAEH,QAAA,MAAM,gBAAgB;;;EAGpB,CAAC;AAEH,iEAAiE;AACjE,QAAA,MAAM,2BAA2B;;;;;EAK/B,CAAC;AAEH,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
|
@@ -11,6 +11,13 @@ const powershellSchema = Type.Object({
|
|
|
11
11
|
command: Type.String({ description: "PowerShell command to execute" }),
|
|
12
12
|
timeout: Type.Optional(Type.Number({ description: "Timeout in seconds (optional, no default timeout)" })),
|
|
13
13
|
});
|
|
14
|
+
/** What a program that calls `bash` or `powershell` receives. */
|
|
15
|
+
const shellStructuredOutputSchema = Type.Object({
|
|
16
|
+
output: Type.String({ description: "Combined stdout and stderr: the retained tail, as the model sees it" }),
|
|
17
|
+
truncated: Type.Boolean({ description: "Whether earlier output was dropped" }),
|
|
18
|
+
fullOutputPath: Type.Optional(Type.String({ description: "File with the complete output, when it was spilled" })),
|
|
19
|
+
exitCode: Type.Number(),
|
|
20
|
+
});
|
|
14
21
|
function validateTimeout(timeout) {
|
|
15
22
|
if (timeout === undefined)
|
|
16
23
|
return;
|
|
@@ -34,7 +41,8 @@ async function prepareExecution(command, options, api, context) {
|
|
|
34
41
|
}
|
|
35
42
|
/**
|
|
36
43
|
* Run each command form in turn until one starts, streaming output to `api.output()` within the retained window, and
|
|
37
|
-
* turn the result into the tool's
|
|
44
|
+
* turn the result into the tool's result: a spill diagnostic, an error result for a nonzero exit, and a thrown error for
|
|
45
|
+
* a failure such as a timeout. The structured output repeats the retained output with the exit code.
|
|
38
46
|
*/
|
|
39
47
|
async function runCommand(commands, execution, timeout, api, context) {
|
|
40
48
|
const env = requireEnv(api);
|
|
@@ -69,27 +77,37 @@ async function runCommand(commands, execution, timeout, api, context) {
|
|
|
69
77
|
throw new Error("Command aborted");
|
|
70
78
|
throw result.error;
|
|
71
79
|
}
|
|
72
|
-
|
|
73
|
-
|
|
80
|
+
const exitCode = result.value.exitCode;
|
|
81
|
+
const retained = api.retainedOutput();
|
|
82
|
+
const structuredOutput = {
|
|
83
|
+
output: retained.text,
|
|
84
|
+
truncated: retained.truncated,
|
|
85
|
+
...(spillPath === undefined ? {} : { fullOutputPath: spillPath }),
|
|
86
|
+
exitCode,
|
|
87
|
+
};
|
|
88
|
+
if (exitCode === 0)
|
|
89
|
+
return { structuredOutput };
|
|
90
|
+
const exited = { severity: "error", code: "exit_code", message: `Command exited with code ${exitCode}` };
|
|
91
|
+
return { structuredOutput, isError: true, diagnostics: [exited] };
|
|
74
92
|
}
|
|
75
93
|
/**
|
|
76
94
|
* Runs a command through the environment's shell. Its output streams to `api.output()`, where the Harness keeps the
|
|
77
95
|
* tail within the default limits; the result content is that retained output. The retained window goes to the
|
|
78
96
|
* environment, which may omit output outside it and report how much it omitted, so dropped counts stay exact. Output
|
|
79
|
-
* beyond the limits is spilled to a file whose path is reported as a diagnostic. A nonzero exit
|
|
80
|
-
* makes an error result that still carries the output and diagnostics.
|
|
97
|
+
* beyond the limits is spilled to a file whose path is reported as a diagnostic. A nonzero exit is an error result with
|
|
98
|
+
* the exit code; a timeout throws, which makes an error result that still carries the output and diagnostics.
|
|
81
99
|
*/
|
|
82
100
|
export function createBashTool(options) {
|
|
83
101
|
return defineTool({
|
|
84
102
|
name: "bash",
|
|
85
103
|
description: `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.`,
|
|
86
104
|
parameters: bashSchema,
|
|
105
|
+
structuredOutputSchema: shellStructuredOutputSchema,
|
|
87
106
|
outputLimits: { retain: "tail" },
|
|
88
107
|
async execute(args, api, context) {
|
|
89
108
|
validateTimeout(args.timeout);
|
|
90
109
|
const execution = await prepareExecution(args.command, options, api, context);
|
|
91
|
-
|
|
92
|
-
return {};
|
|
110
|
+
return runCommand([execution.command], execution, args.timeout, api, context);
|
|
93
111
|
},
|
|
94
112
|
});
|
|
95
113
|
}
|
|
@@ -106,14 +124,14 @@ export function createPowerShellTool(options) {
|
|
|
106
124
|
name: "powershell",
|
|
107
125
|
description: `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.`,
|
|
108
126
|
parameters: powershellSchema,
|
|
127
|
+
structuredOutputSchema: shellStructuredOutputSchema,
|
|
109
128
|
outputLimits: { retain: "tail" },
|
|
110
129
|
async execute(args, api, context) {
|
|
111
130
|
validateTimeout(args.timeout);
|
|
112
131
|
const execution = await prepareExecution(args.command, options, api, context);
|
|
113
132
|
const script = `${UTF8_OUTPUT}\n${execution.command}`;
|
|
114
133
|
const commands = programs.map((program) => [program, ...POWERSHELL_ARGS, script]);
|
|
115
|
-
|
|
116
|
-
return {};
|
|
134
|
+
return runCommand(commands, execution, args.timeout, api, context);
|
|
117
135
|
},
|
|
118
136
|
});
|
|
119
137
|
}
|
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,mBAAmB,GAAG,aAAa,GAAG,IAAI,CAAC;AAEjD,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,yBAAyB,EAAE,CAAC;IAChE,OAAO,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,mDAAmD,EAAE,CAAC,CAAC;CACzG,CAAC,CAAC;AAEH,MAAM,gBAAgB,GAAG,IAAI,CAAC,MAAM,CAAC;IACpC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,+BAA+B,EAAE,CAAC;IACtE,OAAO,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,mDAAmD,EAAE,CAAC,CAAC;CACzG,CAAC,CAAC;AA4BH,SAAS,eAAe,CAAC,OAA2B;IACnD,IAAI,OAAO,KAAK,SAAS;QAAE,OAAO;IAClC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,OAAO,IAAI,CAAC,EAAE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E,YAAY;QAClB,WAAW,EAAE,kIAAkI,iBAAiB,aAAa,iBAAiB,GAAG,IAAI,0HAA0H;QAC/T,UAAU,EAAE,gBAAgB;QAC5B,YAAY,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE;QAChC,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO;YAC/B,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YAC9B,MAAM,SAAS,GAAG,MAAM,gBAAgB,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;YAC9E,MAAM,MAAM,GAAG,GAAG,WAAW,KAAK,SAAS,CAAC,OAAO,EAAE,CAAC;YACtD,MAAM,QAAQ,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,GAAG,eAAe,EAAE,MAAM,CAAC,CAAC,CAAC;YAClF,MAAM,UAAU,CAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,OAAO,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;YAClE,OAAO,EAAE,CAAC;QACX,CAAC;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { Context } from \"@earendil-works/chord\";\nimport { type Static, Type } from \"typebox\";\nimport { defineTool } from \"../harness/define.ts\";\nimport type { ToolExecutionApi, 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\nexport type BashToolInput = Static<typeof bashSchema>;\nexport type PowerShellToolInput = Static<typeof powershellSchema>;\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 outcome: a spill diagnostic, and a thrown error for a failure or a nonzero exit.\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<void> {\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\tif (result.value.exitCode !== 0) throw new Error(`Command exited with code ${result.value.exitCode}`);\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 or timeout throws, which\n * 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\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\tawait runCommand([execution.command], execution, args.timeout, api, context);\n\t\t\treturn {};\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\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\tawait runCommand(commands, execution, args.timeout, api, context);\n\t\t\treturn {};\n\t\t},\n\t});\n}\n"]}
|
|
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,mBAAmB,GAAG,aAAa,GAAG,IAAI,CAAC;AAEjD,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,yBAAyB,EAAE,CAAC;IAChE,OAAO,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,mDAAmD,EAAE,CAAC,CAAC;CACzG,CAAC,CAAC;AAEH,MAAM,gBAAgB,GAAG,IAAI,CAAC,MAAM,CAAC;IACpC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,+BAA+B,EAAE,CAAC;IACtE,OAAO,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,mDAAmD,EAAE,CAAC,CAAC;CACzG,CAAC,CAAC;AAEH,iEAAiE;AACjE,MAAM,2BAA2B,GAAG,IAAI,CAAC,MAAM,CAAC;IAC/C,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,qEAAqE,EAAE,CAAC;IAC3G,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,EAAE,WAAW,EAAE,oCAAoC,EAAE,CAAC;IAC9E,cAAc,EAAE,IAAI,CAAC,QAAQ,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AAM,GAAG,GAAG,WAAW,KAAK,SAAS,CAAC,OAAO,EAAE,CAAC;YACtD,MAAM,QAAQ,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,GAAG,eAAe,EAAE,MAAM,CAAC,CAAC,CAAC;YAClF,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\";\nimport { type Static, Type } from \"typebox\";\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\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"]}
|
package/dist/tools/edit.js
CHANGED
|
@@ -107,7 +107,7 @@ export function createEditTool() {
|
|
|
107
107
|
: { firstChangedLine: diffResult.firstChangedLine }),
|
|
108
108
|
};
|
|
109
109
|
return {
|
|
110
|
-
|
|
110
|
+
output: [{ type: "text", text: `Successfully replaced ${edits.length} block(s) in ${path}.` }],
|
|
111
111
|
details,
|
|
112
112
|
};
|
|
113
113
|
}, context);
|
package/dist/tools/edit.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edit.js","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EACN,6BAA6B,EAC7B,gBAAgB,EAEhB,kBAAkB,EAClB,oBAAoB,EACpB,aAAa,EACb,kBAAkB,EAClB,QAAQ,GACR,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAElD,MAAM,iBAAiB,GAAG,IAAI,CAAC,MAAM,CAAC;IACrC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC;QACpB,WAAW,EACV,uJAAuJ;KACxJ,CAAC;IACF,OAAO,EAAE,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AC,CAAC,EAAE,gBAAgB,EAAE,UAAU,CAAC,gBAAgB,EAAE,CAAC;iBACrD,CAAC;gBACF,OAAO;oBACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,yBAAyB,KAAK,CAAC,MAAM,gBAAgB,IAAI,GAAG,EAAE,CAAC;oBAC/F,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\tcontent: [{ 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,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EACN,6BAA6B,EAC7B,gBAAgB,EAEhB,kBAAkB,EAClB,oBAAoB,EACpB,aAAa,EACb,kBAAkB,EAClB,QAAQ,GACR,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAElD,MAAM,iBAAiB,GAAG,IAAI,CAAC,MAAM,CAAC;IACrC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC;QACpB,WAAW,EACV,uJAAuJ;KACxJ,CAAC;IACF,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,0CAA0C,EAAE,CAAC;CACjF,CAAC,CAAC;AAEH,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,iDAAiD,EAAE,CAAC;IACrF,KAAK,EAAE,IA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P,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"]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** Limits an image the model sees must keep; the defaults below are the coding agent's. */
|
|
2
|
+
export type ImageLimits = {
|
|
3
|
+
/** Pixels. Default 2000. */
|
|
4
|
+
readonly maxWidth: number;
|
|
5
|
+
/** Pixels. Default 2000. */
|
|
6
|
+
readonly maxHeight: number;
|
|
7
|
+
/** Bytes of base64. Default 4.5 MiB, below Anthropic's 5 MB. */
|
|
8
|
+
readonly maxBytes: number;
|
|
9
|
+
};
|
|
10
|
+
export declare const DEFAULT_IMAGE_LIMITS: ImageLimits;
|
|
11
|
+
/** An image the model can take: a supported format, within the limits, as base64. */
|
|
12
|
+
export type PreparedImage = {
|
|
13
|
+
readonly data: string;
|
|
14
|
+
readonly mimeType: string;
|
|
15
|
+
/** Set when the image was resized: its size before and after, for the model to map coordinates back. */
|
|
16
|
+
readonly resized?: {
|
|
17
|
+
readonly from: {
|
|
18
|
+
readonly width: number;
|
|
19
|
+
readonly height: number;
|
|
20
|
+
};
|
|
21
|
+
readonly to: {
|
|
22
|
+
readonly width: number;
|
|
23
|
+
readonly height: number;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
/** The original format, set when it differs from `mimeType`: BMP becomes PNG, a large PNG may become JPEG. */
|
|
27
|
+
readonly convertedFrom?: string;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Decodes, orients, resizes, and re-encodes images so the model can take them. `read` uses one when given; without
|
|
31
|
+
* one, it passes supported images within the byte limit through as they are. `@earendil-works/pi-durable/images`
|
|
32
|
+
* provides a Photon-based one.
|
|
33
|
+
*/
|
|
34
|
+
export type ImageProcessor = {
|
|
35
|
+
/**
|
|
36
|
+
* The image, prepared to fit `limits`, or `undefined` when it cannot be decoded or made to fit. A promise, so a
|
|
37
|
+
* processor can do the work off the event loop.
|
|
38
|
+
*/
|
|
39
|
+
prepare(bytes: Uint8Array, mimeType: string, limits: ImageLimits): Promise<PreparedImage | undefined>;
|
|
40
|
+
};
|
|
41
|
+
/** Formats every provider takes inline; others, such as BMP, need converting. */
|
|
42
|
+
export declare const INLINE_IMAGE_TYPES: ReadonlySet<string>;
|
|
43
|
+
/** Standard base64 of `bytes`, without platform APIs such as `Buffer` or `btoa`. */
|
|
44
|
+
export declare function toBase64(bytes: Uint8Array): string;
|
|
45
|
+
/** The length of the base64 of `byteLength` bytes. */
|
|
46
|
+
export declare function base64Length(byteLength: number): number;
|
|
47
|
+
//# sourceMappingURL=image-processor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image-processor.d.ts","sourceRoot":"","sources":["../../src/tools/image-processor.ts"],"names":[],"mappings":"AAAA,2FAA2F;AAC3F,MAAM,MAAM,WAAW,GAAG;IACzB,4BAA4B;IAC5B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,4BAA4B;IAC5B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,gEAAgE;IAChE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,eAAO,MAAM,oBAAoB,EAAE,WAA8E,CAAC;AAElH,qFAAqF;AACrF,MAAM,MAAM,aAAa,GAAG;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,wGAAwG;IACxG,QAAQ,CAAC,OAAO,CAAC,EAAE;QAClB,QAAQ,CAAC,IAAI,EAAE;YAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;YAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;SAAE,CAAC;QACnE,QAAQ,CAAC,EAAE,EAAE;YAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;YAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;SAAE,CAAC;KACjE,CAAC;IACF,8GAA8G;IAC9G,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;CAChC,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,cAAc,GAAG;IAC5B;;;OAGG;IACH,OAAO,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CAAC;CACtG,CAAC;AAEF,iFAAiF;AACjF,eAAO,MAAM,kBAAkB,EAAE,WAAW,CAAC,MAAM,CAAmE,CAAC;AAIvH,oFAAoF;AACpF,wBAAgB,QAAQ,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAmBlD;AAED,sDAAsD;AACtD,wBAAgB,YAAY,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAEvD"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export const DEFAULT_IMAGE_LIMITS = { maxWidth: 2000, maxHeight: 2000, maxBytes: 4.5 * 1024 * 1024 };
|
|
2
|
+
/** Formats every provider takes inline; others, such as BMP, need converting. */
|
|
3
|
+
export const INLINE_IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
|
|
4
|
+
const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
5
|
+
/** Standard base64 of `bytes`, without platform APIs such as `Buffer` or `btoa`. */
|
|
6
|
+
export function toBase64(bytes) {
|
|
7
|
+
const parts = [];
|
|
8
|
+
let chunk = "";
|
|
9
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
10
|
+
const a = bytes[i];
|
|
11
|
+
const b = bytes[i + 1];
|
|
12
|
+
const c = bytes[i + 2];
|
|
13
|
+
chunk += BASE64[a >> 2];
|
|
14
|
+
chunk += BASE64[((a & 3) << 4) | ((b ?? 0) >> 4)];
|
|
15
|
+
chunk += b === undefined ? "=" : BASE64[((b & 15) << 2) | ((c ?? 0) >> 6)];
|
|
16
|
+
chunk += c === undefined ? "=" : BASE64[c & 63];
|
|
17
|
+
// Join in pieces: one string grown a character at a time is slow for megabytes.
|
|
18
|
+
if (chunk.length >= 8192) {
|
|
19
|
+
parts.push(chunk);
|
|
20
|
+
chunk = "";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
parts.push(chunk);
|
|
24
|
+
return parts.join("");
|
|
25
|
+
}
|
|
26
|
+
/** The length of the base64 of `byteLength` bytes. */
|
|
27
|
+
export function base64Length(byteLength) {
|
|
28
|
+
return Math.ceil(byteLength / 3) * 4;
|
|
29
|
+
}
|
|
30
|
+
//# sourceMappingURL=image-processor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image-processor.js","sourceRoot":"","sources":["../../src/tools/image-processor.ts"],"names":[],"mappings":"AAUA,MAAM,CAAC,MAAM,oBAAoB,GAAgB,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,GAAG,IAAI,GAAG,IAAI,EAAE,CAAC;AA4BlH,iFAAiF;AACjF,MAAM,CAAC,MAAM,kBAAkB,GAAwB,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,YAAY,CAAC,CAAC,CAAC;AAEvH,MAAM,MAAM,GAAG,kEAAkE,CAAC;AAElF,oFAAoF;AACpF,MAAM,UAAU,QAAQ,CAAC,KAAiB;IACzC,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,IAAI,KAAK,GAAG,EAAE,CAAC;IACf,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QAC1C,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAE,CAAC;QACpB,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;QACvB,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;QACvB,KAAK,IAAI,MAAM,CAAC,CAAC,IAAI,CAAC,CAAE,CAAC;QACzB,KAAK,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAE,CAAC;QACnD,KAAK,IAAI,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAE,CAAC;QAC5E,KAAK,IAAI,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAE,CAAC;QACjD,gFAAgF;QAChF,IAAI,KAAK,CAAC,MAAM,IAAI,IAAI,EAAE,CAAC;YAC1B,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YAClB,KAAK,GAAG,EAAE,CAAC;QACZ,CAAC;IACF,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAClB,OAAO,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACvB,CAAC;AAED,sDAAsD;AACtD,MAAM,UAAU,YAAY,CAAC,UAAkB;IAC9C,OAAO,IAAI,CAAC,IAAI,CAAC,UAAU,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;AACtC,CAAC","sourcesContent":["/** Limits an image the model sees must keep; the defaults below are the coding agent's. */\nexport type ImageLimits = {\n\t/** Pixels. Default 2000. */\n\treadonly maxWidth: number;\n\t/** Pixels. Default 2000. */\n\treadonly maxHeight: number;\n\t/** Bytes of base64. Default 4.5 MiB, below Anthropic's 5 MB. */\n\treadonly maxBytes: number;\n};\n\nexport const DEFAULT_IMAGE_LIMITS: ImageLimits = { maxWidth: 2000, maxHeight: 2000, maxBytes: 4.5 * 1024 * 1024 };\n\n/** An image the model can take: a supported format, within the limits, as base64. */\nexport type PreparedImage = {\n\treadonly data: string;\n\treadonly mimeType: string;\n\t/** Set when the image was resized: its size before and after, for the model to map coordinates back. */\n\treadonly resized?: {\n\t\treadonly from: { readonly width: number; readonly height: number };\n\t\treadonly to: { readonly width: number; readonly height: number };\n\t};\n\t/** The original format, set when it differs from `mimeType`: BMP becomes PNG, a large PNG may become JPEG. */\n\treadonly convertedFrom?: string;\n};\n\n/**\n * Decodes, orients, resizes, and re-encodes images so the model can take them. `read` uses one when given; without\n * one, it passes supported images within the byte limit through as they are. `@earendil-works/pi-durable/images`\n * provides a Photon-based one.\n */\nexport type ImageProcessor = {\n\t/**\n\t * The image, prepared to fit `limits`, or `undefined` when it cannot be decoded or made to fit. A promise, so a\n\t * processor can do the work off the event loop.\n\t */\n\tprepare(bytes: Uint8Array, mimeType: string, limits: ImageLimits): Promise<PreparedImage | undefined>;\n};\n\n/** Formats every provider takes inline; others, such as BMP, need converting. */\nexport const INLINE_IMAGE_TYPES: ReadonlySet<string> = new Set([\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"]);\n\nconst BASE64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n/** Standard base64 of `bytes`, without platform APIs such as `Buffer` or `btoa`. */\nexport function toBase64(bytes: Uint8Array): string {\n\tconst parts: string[] = [];\n\tlet chunk = \"\";\n\tfor (let i = 0; i < bytes.length; i += 3) {\n\t\tconst a = bytes[i]!;\n\t\tconst b = bytes[i + 1];\n\t\tconst c = bytes[i + 2];\n\t\tchunk += BASE64[a >> 2]!;\n\t\tchunk += BASE64[((a & 3) << 4) | ((b ?? 0) >> 4)]!;\n\t\tchunk += b === undefined ? \"=\" : BASE64[((b & 15) << 2) | ((c ?? 0) >> 6)]!;\n\t\tchunk += c === undefined ? \"=\" : BASE64[c & 63]!;\n\t\t// Join in pieces: one string grown a character at a time is slow for megabytes.\n\t\tif (chunk.length >= 8192) {\n\t\t\tparts.push(chunk);\n\t\t\tchunk = \"\";\n\t\t}\n\t}\n\tparts.push(chunk);\n\treturn parts.join(\"\");\n}\n\n/** The length of the base64 of `byteLength` bytes. */\nexport function base64Length(byteLength: number): number {\n\treturn Math.ceil(byteLength / 3) * 4;\n}\n"]}
|
package/dist/tools/image.d.ts
CHANGED
|
@@ -9,4 +9,12 @@ export type ByteSource = {
|
|
|
9
9
|
*/
|
|
10
10
|
export declare function detectSupportedImageMimeTypeOf(source: ByteSource): Promise<string | undefined>;
|
|
11
11
|
export declare function detectSupportedImageMimeType(buffer: Uint8Array): string | undefined;
|
|
12
|
+
/**
|
|
13
|
+
* The width and height an image of `mimeType` declares in its header, without decoding it: PNG's IHDR, GIF's screen,
|
|
14
|
+
* WebP's VP8, VP8L, or VP8X chunk, JPEG's first SOF segment. `undefined` when the header cannot be read.
|
|
15
|
+
*/
|
|
16
|
+
export declare function imageDimensions(bytes: Uint8Array, mimeType: string): {
|
|
17
|
+
readonly width: number;
|
|
18
|
+
readonly height: number;
|
|
19
|
+
} | undefined;
|
|
12
20
|
//# sourceMappingURL=image.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"image.d.ts","sourceRoot":"","sources":["../../src/tools/image.ts"],"names":[],"mappings":"AAKA,kDAAkD;AAClD,MAAM,MAAM,UAAU,GAAG;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CAC1D,CAAC;AAEF;;;GAGG;AACH,wBAAsB,8BAA8B,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAIpG;AA0BD,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,GAAG,SAAS,CAOnF"}
|
|
1
|
+
{"version":3,"file":"image.d.ts","sourceRoot":"","sources":["../../src/tools/image.ts"],"names":[],"mappings":"AAKA,kDAAkD;AAClD,MAAM,MAAM,UAAU,GAAG;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CAC1D,CAAC;AAEF;;;GAGG;AACH,wBAAsB,8BAA8B,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAIpG;AA0BD,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,GAAG,SAAS,CAOnF;AAsBD;;;GAGG;AACH,wBAAgB,eAAe,CAC9B,KAAK,EAAE,UAAU,EACjB,QAAQ,EAAE,MAAM,GACd;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAqCjE"}
|