@codeworksh/plugin 0.1.0-dev.20261007133154 → 0.2.0-canary.8.1.g763b062a

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/sandbox/io.mjs CHANGED
@@ -1,127 +1,3 @@
1
- import { t as __exportAll } from "../rolldown-runtime-D7D4PA-g.mjs";
2
- import { ID } from "./instance.mjs";
3
- import { posix } from "../posix.mjs";
4
- import { Service, withCwd } from "./filesystem.mjs";
5
- import { Shell as Shell$1, withCwd as withCwd$1 } from "./shell.mjs";
6
- import { Context, Effect, Layer } from "effect";
7
- //#region src/sandbox/io.ts
8
- var io_exports = /* @__PURE__ */ __exportAll({
9
- Current: () => Current,
10
- FileSystem: () => FileSystem,
11
- SandboxIO: () => io_exports,
12
- Shell: () => Shell,
13
- host: () => host,
14
- hostLayer: () => hostLayer,
15
- identityLayer: () => identityLayer,
16
- mount: () => mount,
17
- remote: () => remote,
18
- resolveMountCwd: () => resolveMountCwd,
19
- virtual: () => virtual
20
- });
21
- /**
22
- * `SandboxIO` is a **mount**: a filesystem, a shell, and the identity and
23
- * working directory they act on.
24
- *
25
- * It is the whole vocabulary a consumer needs. Project, Git, Copy, Location, and
26
- * every tool ask for `SandboxIO.FileSystem`, `SandboxIO.Shell`, and
27
- * `SandboxIO.Current` — never for a driver, an address, or a provider SDK — so
28
- * a host directory, an in-memory VFS, and a remote microVM are interchangeable
29
- * behind one contract.
30
- *
31
- * The mount neither creates nor destroys infrastructure. `SandboxInstance` is
32
- * the durable namespace it acts on — a device, which exists whether or not
33
- * anything has it mounted — and `Sandbox.Controller` is the only path that
34
- * creates, stops, or destroys one.
35
- */
36
- /**
37
- * The filesystem tag. Re-exported here so consumers import one namespace —
38
- * Project, Git, Copy, and the runner ask for `SandboxIO.FileSystem`, never for
39
- * the module that happens to define it. Code *inside* `sandbox/` keeps importing
40
- * the tag directly, since `io.ts` is built on top of it.
41
- */
42
- const FileSystem = Service;
43
- /** The shell tag. Re-exported here so consumers import one namespace. */
44
- const Shell = Shell$1;
45
- /** Identity and working directory of the current mount. */
46
- var Current = class extends Context.Service()("@codeworksh/plugin/sandbox/io/Current") {};
47
- /**
48
- * Resolve a mount's cwd without consulting ambient process state.
49
- *
50
- * The default is supplied by the namespace adapter:
51
- * provider metadata remotely, `/` for a virtual filesystem, and `process.cwd()` for the host adapter.
52
- * An explicit absolute cwd replaces it; a relative cwd is resolved inside it. The
53
- * result is therefore always the one concrete absolute path `Current` requires.
54
- *
55
- * A non-absolute default throws rather than failing typed. It is the one
56
- * defect-level guard in this module, and deliberately so:
57
- * Adapters reading a value from a provider call this inside their own error channel,
58
- * where the throw becomes their typed failure (see `EnvDaytona.mountCwd`).
59
- */
60
- const resolveMountCwd = (defaultCwd, cwd) => {
61
- if (!posix.isAbsolute(defaultCwd)) throw new TypeError(`Sandbox default cwd must be absolute: ${defaultCwd}`);
62
- if (cwd === void 0) return posix.resolve(defaultCwd);
63
- return posix.isAbsolute(cwd) ? posix.resolve(cwd) : posix.resolve(defaultCwd, cwd);
64
- };
65
- /**
66
- * Bind a cwd-neutral transport to one mount.
67
- *
68
- * The transport underneath is shared between
69
- * mounts and stays rooted at the namespace root, and everything directory-shaped
70
- * happens here, once per mount. Two mounts of one namespace at different working
71
- * directories therefore coexist without seeing or moving each other's.
72
- *
73
- * It consumes the same two tags it provides — the transport is supplied by the
74
- * layer this is composed over, not by itself.
75
- */
76
- const mount = (identity) => Layer.mergeAll(Layer.succeed(Current, identity), Layer.effect(Service, Effect.map(Service, (fs) => withCwd(fs, identity.cwd))), Layer.effect(Shell$1, Effect.map(Shell$1, (shell) => withCwd$1(shell, identity.cwd))));
77
- /**
78
- * Just the identity tag, with no filesystem or shell beneath it. For consumers
79
- * assembled from stubs — a test that runs `Project` over a fake filesystem still
80
- * needs to know which namespace it is in.
81
- */
82
- const identityLayer = (identity) => Layer.succeed(Current, identity);
83
- /** The host identity alone. See {@link identityLayer}. */
84
- const hostLayer = (cwd) => identityLayer(host(cwd));
85
- /**
86
- * The host, rooted at `cwd`. Always `SandboxInstance.ID.local`: the working
87
- * directory selects where relative paths resolve, it does not make a second host
88
- * namespace — two mounts rooted at different directories still agree on absolute
89
- * paths.
90
- *
91
- * The host coordinate is explicit so a caller cannot accidentally substitute ambient process
92
- * state for the application or session directory it owns.
93
- */
94
- const host = (cwd) => ({
95
- id: ID.local,
96
- driver: "local",
97
- kind: "local",
98
- cwd: resolveMountCwd(cwd)
99
- });
100
- /**
101
- * A VFS-backed namespace. The id is minted per call unless one is named, because
102
- * building one of these builds a fresh VFS: N unnamed calls are N distinct
103
- * namespaces, none of which outlives the process. A file-backed store is the
104
- * exception — its file is the state, so whoever knows the file supplies the id
105
- * it was registered under.
106
- */
107
- const virtual = (input) => ({
108
- id: input.id ?? ID.create(),
109
- driver: input.driver,
110
- kind: "virtual",
111
- cwd: resolveMountCwd(input.defaultCwd ?? "/", input.cwd)
112
- });
113
- /**
114
- * A provider-hosted namespace. The id is always supplied: a remote resource's
115
- * durable identity is minted and recorded by whoever provisioned it, never
116
- * derived here from the provider's own locator.
117
- */
118
- const remote = (input) => ({
119
- id: input.id,
120
- driver: input.driver,
121
- kind: "remote",
122
- cwd: resolveMountCwd(input.defaultCwd, input.cwd)
123
- });
124
- //#endregion
125
- export { Current, FileSystem, io_exports as SandboxIO, Shell, host, hostLayer, identityLayer, mount, remote, resolveMountCwd, virtual };
126
-
127
- //# sourceMappingURL=io.mjs.map
1
+ import "./instance.mjs";
2
+ import { a as Shell, c as identityLayer, d as remote, f as resolveMountCwd, i as Mutation, l as io_exports, m as withMutation, n as DEFAULT_SPILL_PATH, o as host, p as virtual, r as FileSystem, s as hostLayer, t as Current, u as mount } from "../io-Dgh8U41k.mjs";
3
+ export { Current, DEFAULT_SPILL_PATH, FileSystem, Mutation, io_exports as SandboxIO, Shell, host, hostLayer, identityLayer, mount, remote, resolveMountCwd, virtual, withMutation };
package/sandbox.d.mts CHANGED
@@ -1,12 +1,12 @@
1
- import { A as apiVersion, C as Observed, D as RuntimeConfigBase, E as Registration, I as Redactor, M as driver, O as RuntimeInput, S as Name, _ as Capabilities, a as Provides, at as providerError, b as Module, ct as sanitizeError, g as ApiVersion, h as AbsolutePath, i as Layer, it as makeRedactor, j as defineModule, n as FileSystem, o as Shell, ot as providerErrorCause, q as SandboxProviderError, r as Identity, st as providerErrorIsNotFound, t as Current, v as Definition, vt as instance_d_exports, w as Provisioned, x as ModuleDefinition, y as Driver } from "./io-BYs7hbiY.mjs";
2
- import { c as filesystem_d_exports } from "./filesystem-Cp-KapCE.mjs";
1
+ import { A as RuntimeConfigBase, C as Module, D as Provisioned, E as Observed, F as driver, N as apiVersion, P as defineModule, S as Driver, T as Name, X as SandboxProviderError, _ as withMutation, a as Layer, b as Capabilities, c as Shell, ct as providerError, dt as sanitizeError, i as Identity, j as RuntimeInput, k as Registration, lt as providerErrorCause, n as DEFAULT_SPILL_PATH, o as Mutation, r as FileSystem, s as Provides, st as makeRedactor, t as Current, ut as providerErrorIsNotFound, v as AbsolutePath, w as ModuleDefinition, x as Definition, xt as instance_d_exports, y as ApiVersion, z as Redactor } from "./io-nhvNKC33.mjs";
2
+ import { c as filesystem_d_exports } from "./filesystem-CuGE9poU.mjs";
3
3
  import { a as ShellError, i as Shell$1, l as quote, n as ExecResult, o as ShellOptions, r as ISandboxExe, s as fromExec, t as ExecChunk, u as quoteArgv } from "./shell-CZ6Y4lNU.mjs";
4
4
  import { SandboxResource as resource_d_exports } from "./sandbox/resource.mjs";
5
5
  declare namespace driver_d_exports {
6
6
  export { AbsolutePath, ApiVersion, Capabilities, Definition, Driver, Module, ModuleDefinition, Name, Observed, Provisioned, Registration, RuntimeConfigBase as RuntimeConfig, RuntimeConfigBase, RuntimeInput, driver_d_exports as SandboxDriver, apiVersion, driver, defineModule as module };
7
7
  }
8
8
  declare namespace io_d_exports {
9
- export { Current, FileSystem, Identity, Layer, Provides, io_d_exports as SandboxIO, Shell };
9
+ export { Current, DEFAULT_SPILL_PATH, FileSystem, Identity, Layer, Mutation, Provides, io_d_exports as SandboxIO, Shell, withMutation };
10
10
  }
11
11
  declare namespace provider_d_exports {
12
12
  export { Redactor, SandboxProviderError, makeRedactor, providerError, providerErrorCause, providerErrorIsNotFound, sanitizeError };
package/sandbox.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { SandboxInstance as instance_exports } from "./sandbox/instance.mjs";
3
- import { SandboxFileSystem as filesystem_exports } from "./sandbox/filesystem.mjs";
4
- import { Shell, ShellError, fromExec, quote, quoteArgv } from "./sandbox/shell.mjs";
5
- import { Current, FileSystem, Shell as Shell$1 } from "./sandbox/io.mjs";
3
+ import { i as filesystem_exports } from "./filesystem-omtKo08x.mjs";
4
+ import { a as Shell, i as Mutation, m as withMutation, n as DEFAULT_SPILL_PATH, r as FileSystem, t as Current } from "./io-Dgh8U41k.mjs";
5
+ import { Shell as Shell$1, ShellError, fromExec, quote, quoteArgv } from "./sandbox/shell.mjs";
6
6
  import { AbsolutePath, Name, RuntimeConfigBase, driver, module as defineModule } from "./sandbox/driver.mjs";
7
7
  import { SandboxProviderError, makeRedactor, providerError, providerErrorCause, providerErrorIsNotFound, sanitizeError } from "./sandbox/errors.mjs";
8
8
  import { SandboxResource as resource_exports } from "./sandbox/resource.mjs";
@@ -20,9 +20,12 @@ var driver_exports = /* @__PURE__ */ __exportAll({
20
20
  //#region src/sandbox/public/io.ts
21
21
  var io_exports = /* @__PURE__ */ __exportAll({
22
22
  Current: () => Current,
23
+ DEFAULT_SPILL_PATH: () => DEFAULT_SPILL_PATH,
23
24
  FileSystem: () => FileSystem,
25
+ Mutation: () => Mutation,
24
26
  SandboxIO: () => io_exports,
25
- Shell: () => Shell$1
27
+ Shell: () => Shell,
28
+ withMutation: () => withMutation
26
29
  });
27
30
  //#endregion
28
31
  //#region src/sandbox/provider.ts
@@ -37,7 +40,7 @@ var provider_exports = /* @__PURE__ */ __exportAll({
37
40
  //#endregion
38
41
  //#region src/sandbox/public/shell.ts
39
42
  var shell_exports = /* @__PURE__ */ __exportAll({
40
- Shell: () => Shell,
43
+ Shell: () => Shell$1,
41
44
  ShellError: () => ShellError,
42
45
  fromExec: () => fromExec,
43
46
  quote: () => quote,
package/sandbox.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox.mjs","names":[],"sources":["../../src/sandbox/public/driver.ts","../../src/sandbox/public/io.ts","../../src/sandbox/provider.ts","../../src/sandbox/public/shell.ts"],"sourcesContent":["export { AbsolutePath, apiVersion, driver, module, Name, RuntimeConfigBase } from \"../driver.ts\";\nexport type {\n\tApiVersion,\n\tCapabilities,\n\tDefinition,\n\tDriver,\n\tModule,\n\tModuleDefinition,\n\tObserved,\n\tProvisioned,\n\tRegistration,\n\tRuntimeConfigBase as RuntimeConfig,\n\tRuntimeInput,\n} from \"../driver.ts\";\n\nexport * as SandboxDriver from \"./driver.ts\";\n","export { Current, FileSystem, Shell } from \"../io.ts\";\nexport type { Identity, Layer, Provides } from \"../io.ts\";\n\nexport * as SandboxIO from \"./io.ts\";\n","export {\n\tmakeRedactor,\n\tproviderError,\n\tproviderErrorCause,\n\tproviderErrorIsNotFound,\n\tSandboxProviderError,\n\tsanitizeError,\n} from \"./errors.ts\";\nexport type { Redactor } from \"./errors.ts\";\n","export { fromExec, quote, quoteArgv, Shell, ShellError } from \"../shell.ts\";\nexport type { ExecChunk, ExecResult, ISandboxExe, ShellOptions } from \"../shell.ts\";\n"],"mappings":""}
1
+ {"version":3,"file":"sandbox.mjs","names":[],"sources":["../../src/sandbox/public/driver.ts","../../src/sandbox/public/io.ts","../../src/sandbox/provider.ts","../../src/sandbox/public/shell.ts"],"sourcesContent":["export { AbsolutePath, apiVersion, driver, module, Name, RuntimeConfigBase } from \"../driver.ts\";\nexport type {\n\tApiVersion,\n\tCapabilities,\n\tDefinition,\n\tDriver,\n\tModule,\n\tModuleDefinition,\n\tObserved,\n\tProvisioned,\n\tRegistration,\n\tRuntimeConfigBase as RuntimeConfig,\n\tRuntimeInput,\n} from \"../driver.ts\";\n\nexport * as SandboxDriver from \"./driver.ts\";\n","export { Current, DEFAULT_SPILL_PATH, FileSystem, Mutation, Shell, withMutation } from \"../io.ts\";\nexport type { Identity, Layer, Provides } from \"../io.ts\";\n\nexport * as SandboxIO from \"./io.ts\";\n","export {\n\tmakeRedactor,\n\tproviderError,\n\tproviderErrorCause,\n\tproviderErrorIsNotFound,\n\tSandboxProviderError,\n\tsanitizeError,\n} from \"./errors.ts\";\nexport type { Redactor } from \"./errors.ts\";\n","export { fromExec, quote, quoteArgv, Shell, ShellError } from \"../shell.ts\";\nexport type { ExecChunk, ExecResult, ISandboxExe, ShellOptions } from \"../shell.ts\";\n"],"mappings":""}
@@ -11,6 +11,7 @@ declare const requestFields: {
11
11
  cacheRetention: Schema.optional<Schema.Literals<readonly ["none", "short", "long"]>>;
12
12
  headers: Schema.optional<Schema.$Record<Schema.String, Schema.String>>;
13
13
  timeoutMs: Schema.optional<Schema.Finite>;
14
+ idleTimeoutMs: Schema.optional<Schema.Finite>;
14
15
  maxRetries: Schema.optional<Schema.Finite>;
15
16
  metadata: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
16
17
  thinkingBudgets: Schema.optional<Schema.$Record<Schema.Literals<("high" | "low" | "max" | "medium" | "minimal" | "xhigh")[]>, Schema.optional<Schema.Finite>>>;
@@ -28,6 +29,7 @@ declare const Block: Schema.StructWithRest<Schema.Struct<{
28
29
  readonly cacheRetention: Schema.optional<Schema.Literals<readonly ["none", "short", "long"]>>;
29
30
  readonly headers: Schema.optional<Schema.$Record<Schema.String, Schema.String>>;
30
31
  readonly timeoutMs: Schema.optional<Schema.Finite>;
32
+ readonly idleTimeoutMs: Schema.optional<Schema.Finite>;
31
33
  readonly maxRetries: Schema.optional<Schema.Finite>;
32
34
  readonly metadata: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
33
35
  readonly thinkingBudgets: Schema.optional<Schema.$Record<Schema.Literals<("high" | "low" | "max" | "medium" | "minimal" | "xhigh")[]>, Schema.optional<Schema.Finite>>>;
@@ -54,6 +56,7 @@ declare const Model$1: Schema.Struct<{
54
56
  readonly cacheRetention: Schema.optional<Schema.Literals<readonly ["none", "short", "long"]>>;
55
57
  readonly headers: Schema.optional<Schema.$Record<Schema.String, Schema.String>>;
56
58
  readonly timeoutMs: Schema.optional<Schema.Finite>;
59
+ readonly idleTimeoutMs: Schema.optional<Schema.Finite>;
57
60
  readonly maxRetries: Schema.optional<Schema.Finite>;
58
61
  readonly metadata: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
59
62
  readonly thinkingBudgets: Schema.optional<Schema.$Record<Schema.Literals<("high" | "low" | "max" | "medium" | "minimal" | "xhigh")[]>, Schema.optional<Schema.Finite>>>;
@@ -73,6 +76,7 @@ declare const Model$1: Schema.Struct<{
73
76
  readonly cacheRetention: Schema.optional<Schema.Literals<readonly ["none", "short", "long"]>>;
74
77
  readonly headers: Schema.optional<Schema.$Record<Schema.String, Schema.String>>;
75
78
  readonly timeoutMs: Schema.optional<Schema.Finite>;
79
+ readonly idleTimeoutMs: Schema.optional<Schema.Finite>;
76
80
  readonly maxRetries: Schema.optional<Schema.Finite>;
77
81
  readonly metadata: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
78
82
  readonly thinkingBudgets: Schema.optional<Schema.$Record<Schema.Literals<("high" | "low" | "max" | "medium" | "minimal" | "xhigh")[]>, Schema.optional<Schema.Finite>>>;
@@ -313,6 +317,7 @@ declare const Patch: Schema.Struct<{
313
317
  readonly cacheRetention: Schema.optional<Schema.Literals<readonly ["none", "short", "long"]>>;
314
318
  readonly headers: Schema.optional<Schema.$Record<Schema.String, Schema.String>>;
315
319
  readonly timeoutMs: Schema.optional<Schema.Finite>;
320
+ readonly idleTimeoutMs: Schema.optional<Schema.Finite>;
316
321
  readonly maxRetries: Schema.optional<Schema.Finite>;
317
322
  readonly metadata: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
318
323
  readonly thinkingBudgets: Schema.optional<Schema.$Record<Schema.Literals<("high" | "low" | "max" | "medium" | "minimal" | "xhigh")[]>, Schema.optional<Schema.Finite>>>;
@@ -332,6 +337,7 @@ declare const Patch: Schema.Struct<{
332
337
  readonly cacheRetention: Schema.optional<Schema.Literals<readonly ["none", "short", "long"]>>;
333
338
  readonly headers: Schema.optional<Schema.$Record<Schema.String, Schema.String>>;
334
339
  readonly timeoutMs: Schema.optional<Schema.Finite>;
340
+ readonly idleTimeoutMs: Schema.optional<Schema.Finite>;
335
341
  readonly maxRetries: Schema.optional<Schema.Finite>;
336
342
  readonly metadata: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
337
343
  readonly thinkingBudgets: Schema.optional<Schema.$Record<Schema.Literals<("high" | "low" | "max" | "medium" | "minimal" | "xhigh")[]>, Schema.optional<Schema.Finite>>>;
@@ -578,4 +584,4 @@ interface Info {
578
584
  declare const defaults: Info;
579
585
  //#endregion
580
586
  export { keyName as _, KeyReference as a, ModelProtocol as c, PluginPatch as d, Retry as f, defaults as g, ToolExecution as h, Info as i, Patch as l, ThinkingLevel as m, Declared as n, Model$1 as o, RetryPolicy as p, DeclaredModel as r, ModelEntry as s, Block as t, PluginEntry as u, requestFields as v };
581
- //# sourceMappingURL=settings-B6-grSTA.d.mts.map
587
+ //# sourceMappingURL=settings-47Mzxhl0.d.mts.map
package/settings.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { _ as keyName, a as KeyReference, c as ModelProtocol, d as PluginPatch, f as Retry, g as defaults, h as ToolExecution, i as Info, l as Patch, m as ThinkingLevel, n as Declared, o as Model, p as RetryPolicy, r as DeclaredModel, s as ModelEntry, t as Block, u as PluginEntry, v as requestFields } from "./settings-B6-grSTA.mjs";
1
+ import { _ as keyName, a as KeyReference, c as ModelProtocol, d as PluginPatch, f as Retry, g as defaults, h as ToolExecution, i as Info, l as Patch, m as ThinkingLevel, n as Declared, o as Model, p as RetryPolicy, r as DeclaredModel, s as ModelEntry, t as Block, u as PluginEntry, v as requestFields } from "./settings-47Mzxhl0.mjs";
2
2
  export { Block, Declared, DeclaredModel, Info, KeyReference, Model, ModelEntry, ModelProtocol, Patch, PluginEntry, PluginPatch, Retry, RetryPolicy, ThinkingLevel, ToolExecution, defaults, keyName, requestFields };
package/settings.mjs CHANGED
@@ -16,6 +16,7 @@ const requestFields = {
16
16
  ])),
17
17
  headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),
18
18
  timeoutMs: Schema.optional(Schema.Finite),
19
+ idleTimeoutMs: Schema.optional(Schema.Finite),
19
20
  maxRetries: Schema.optional(Schema.Finite),
20
21
  metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
21
22
  thinkingBudgets: Schema.optional(Budgets),
@@ -136,6 +137,7 @@ const defaults = {
136
137
  toolExecution: "sequential",
137
138
  options: {
138
139
  timeoutMs: 36e5,
140
+ idleTimeoutMs: 3e5,
139
141
  maxRetries: 0
140
142
  }
141
143
  },
package/settings.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"settings.mjs","names":["AikitModel"],"sources":["../../src/settings.ts"],"sourcesContent":["import { Model as AikitModel, type Protocol } from \"@codeworksh/aikit\";\nimport { Effect, Schema, type SchemaAST, SchemaGetter, SchemaIssue } from \"effect\";\nimport { isAikitModelInfo, NonNegativeInt, validateAikitModelInfo } from \"./schema.ts\";\n\nexport const ThinkingLevel = Schema.Literals(Object.values(AikitModel.ThinkingLevelEnum));\nexport const ToolExecution = Schema.Literals([\"sequential\", \"parallel\"]);\nexport type ToolExecution = typeof ToolExecution.Type;\nconst Budgets = Schema.Record(\n\tSchema.Literals(Object.values(AikitModel.ThinkingLevelEnum).filter((level) => level !== \"off\")),\n\tSchema.optional(Schema.Finite),\n);\n\n/** Aikit does not export its request schema; keep this routing surface checked against its public types. */\nexport const requestFields = {\n\ttemperature: Schema.optional(Schema.Finite),\n\tmaxTokens: Schema.optional(Schema.Finite),\n\tcacheRetention: Schema.optional(Schema.Literals([\"none\", \"short\", \"long\"])),\n\theaders: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n\ttimeoutMs: Schema.optional(Schema.Finite),\n\tmaxRetries: Schema.optional(Schema.Finite),\n\tmetadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n\tthinkingBudgets: Schema.optional(Budgets),\n\tbaseURL: Schema.optional(Schema.String),\n\tmethod: Schema.optional(Schema.Literals(Object.values(AikitModel.APIMethodEnum))),\n} satisfies Record<\n\t| Exclude<keyof Protocol.CommonOptions, \"signal\" | \"sessionId\" | \"reasoning\" | \"apiKey\" | \"onPayload\">\n\t| \"baseURL\"\n\t| \"method\",\n\tSchema.Top\n>;\n\n/**\n * An API key named, never written: `\"${NAME}\"`, read from the host process environment when the\n * model is called. Settings only ever hold the variable's name.\n */\nconst keyReference = /^\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}$/;\nconst keyReferenceError = 'apiKey must reference an environment variable, e.g. \"${OPENAI_API_KEY}\"';\nexport const KeyReference = Schema.String.check(\n\tSchema.makeFilter((value) => keyReference.test(value) || keyReferenceError),\n);\n\n/** The variable a `\"${NAME}\"` reference names. */\nexport const keyName = (reference: string): string => keyReference.exec(reference)?.[1] ?? reference;\n\nconst reserved = new Set([\n\t\"toolChoice\",\n\t\"activeTools\",\n\t\"provider\",\n\t\"id\",\n\t\"signal\",\n\t\"sessionId\",\n\t\"reasoning\",\n\t\"modelId\",\n\t\"onPayload\",\n\t\"api\",\n\t\"npm\",\n\t\"providerOptionsKey\",\n\t\"compat\",\n\t\"thinkingLevelMap\",\n]);\n\n/** The wire protocol a model speaks, which a catalog entry may have wrong for a local endpoint. */\nexport const ModelProtocol = Schema.Literals(Object.values(AikitModel.KnownProviderEnum));\n\nexport const Block = Schema.StructWithRest(\n\tSchema.Struct({\n\t\t...requestFields,\n\t\tprotocol: Schema.optional(ModelProtocol),\n\t\tthinkingLevel: Schema.optional(ThinkingLevel),\n\t\ttoolExecution: Schema.optional(ToolExecution),\n\t\tcontextWindow: Schema.optional(Schema.Finite),\n\t\t/** Which environment variable holds the key for this model: `\"${NAME}\"`. */\n\t\tapiKey: Schema.optional(KeyReference),\n\t\textras: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n\t}),\n\t[Schema.Record(Schema.String, Schema.Unknown)],\n).check(\n\tSchema.makeFilter(\n\t\t(value) => Object.keys(value).every((key) => !reserved.has(key)) || \"Reserved configuration key in model options\",\n\t),\n);\nexport type Block = typeof Block.Type;\n\nexport const Model = Schema.Struct({\n\tprovider: Schema.optional(Schema.String),\n\tid: Schema.optional(Schema.String),\n\tthinkingLevel: Schema.optional(ThinkingLevel),\n\ttoolExecution: Schema.optional(ToolExecution),\n\tthinkingBudgets: Schema.optional(Budgets),\n\toptions: Schema.optional(Block),\n\tproviderOptions: Schema.optional(Schema.Record(Schema.String, Schema.Record(Schema.String, Block))),\n});\nconst reasonOf = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause));\n\nconst decodeModelEntry = (value: unknown, options: SchemaAST.ParseOptions) =>\n\tEffect.try({\n\t\ttry: () => {\n\t\t\tconst entry = validateAikitModelInfo(value, \"models entry\");\n\t\t\tif (entry.provider.key !== undefined && !keyReference.test(entry.provider.key)) {\n\t\t\t\tthrow new Error(`models entry ${entry.provider.id}/${entry.id}: provider.key: ${keyReferenceError}`);\n\t\t\t}\n\t\t\treturn entry;\n\t\t},\n\t\tcatch: (cause) => new SchemaIssue.InvalidValue({ message: reasonOf(cause) }, value, options),\n\t});\n\n/**\n * A catalog entry in settings: an aikit `Model.Info`, read exactly like an entry of the generated\n * catalog. The one difference is `provider.key`, which must be a `\"${NAME}\"` reference.\n */\nexport const ModelEntry = Schema.Unknown.pipe(\n\tSchema.decodeTo(Schema.declare<AikitModel.Info>(isAikitModelInfo, { expected: \"aikit Model.Info\" }), {\n\t\tdecode: SchemaGetter.transformEffect(decodeModelEntry),\n\t\tencode: SchemaGetter.transformEffect(decodeModelEntry),\n\t}),\n);\nexport type ModelEntry = typeof ModelEntry.Type;\n\n/** A module to load: a path, a `file:` URL, or a package spec. */\nconst PluginReference = Schema.String.check(Schema.isNonEmpty());\n/**\n * Configuration for a plugin something else already selected, named by its ID (`plugin`) or by\n * its registered module string (`package`). It never loads anything: an entry naming a plugin\n * that is not in the selection is ignored.\n */\nconst config = {\n\tenabled: Schema.optional(Schema.Boolean),\n\toptions: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n};\nexport const PluginPatch = Schema.Union(\n\t[Schema.Struct({ plugin: PluginReference, ...config }), Schema.Struct({ package: PluginReference, ...config })],\n\t// `oneOf`, so an entry carrying both keys is a decode failure rather than one of them being\n\t// quietly dropped -- naming a plugin two ways at once says two different things.\n\t{ mode: \"oneOf\" },\n);\nexport const PluginEntry = Schema.Union([PluginReference, PluginPatch]);\nexport type PluginEntry = typeof PluginEntry.Type;\n\n/**\n * Agent-level retry of a turn whose provider request failed transiently (rate limit, overload,\n * 5xx, dropped connection). Delays double from `baseDelayMs` and stop growing at `maxDelayMs`;\n * a server that asks for a longer wait than `maxDelayMs` is not retried. `maxRetries: 0` is off.\n *\n * Separate from `model.options.maxRetries`, which retries inside the provider SDK and defaults to\n * 0 so that the two do not multiply, and so a quota error reaches the loop instead of being retried.\n */\nexport const Retry = Schema.Struct({\n\tmaxRetries: Schema.optional(NonNegativeInt),\n\tbaseDelayMs: Schema.optional(NonNegativeInt),\n\tmaxDelayMs: Schema.optional(NonNegativeInt),\n});\nexport interface RetryPolicy {\n\treadonly maxRetries: number;\n\treadonly baseDelayMs: number;\n\treadonly maxDelayMs: number;\n}\n\nexport const Patch = Schema.Struct({\n\t$schema: Schema.optional(Schema.String),\n\tplugins: Schema.optional(Schema.Array(PluginEntry)),\n\tmodel: Schema.optional(Model),\n\tmodels: Schema.optional(Schema.Array(ModelEntry)),\n\tretry: Schema.optional(Retry),\n});\nexport type Patch = typeof Patch.Type;\n\n/**\n * One plugin entry, and where it came from.\n *\n * Flattening every layer's `plugins` into one array loses the file that declared each entry, and\n * that cannot be recovered afterwards: two layers may declare the same string, so attribution is\n * genuinely gone rather than merely inconvenient. Three things need it -- anchoring a relative\n * path, naming the declaring layer in `plugin list`, and the missing-plugin diagnostic -- so the\n * loaded shape carries it from the start.\n *\n * In simple terms:\n * `written` - is what module the developer is declaring - what\n * `file` - where the module is being declared - where\n * `entry` - the resolved path of the module, relative to the `file`; especially needed for local.\n *\n * Example:\n * written: \"@acme/x@^1\"\n * entry: \"@acme/x@^1\"\n * file: \"/Users/me/.codework/settings.jsonc\"\n *\n * written: \"./plugins/mine.mjs\"\n * entry: \"/Users/me/.codework/plugins/mine.mjs\"\n * file: \"/Users/me/.codework/settings.jsonc\"\n */\nexport interface Declared {\n\t/** The entry exactly as the file spells it, which is the string a person will search for. */\n\treadonly written: PluginEntry;\n\t/** The same entry with any relative path anchored to the directory of its declaring file. */\n\treadonly entry: PluginEntry;\n\t/** The settings file that declared it. */\n\treadonly file: string;\n}\n\n/** A `models` entry, and the settings file that declared it. */\nexport interface DeclaredModel {\n\treadonly entry: AikitModel.Info;\n\treadonly file: string;\n}\n\nexport interface Info {\n\t/**\n\t * Plugin entries added to the harness selection, in order: every layer's entries, lowest\n\t * priority first, so a project's list extends the user's rather than replacing it.\n\t *\n\t * Anchored, and stripped of provenance: this is the list the loader consumes. {@link Info.declared}\n\t * is the same list with the file each entry came from.\n\t */\n\treadonly plugins: ReadonlyArray<PluginEntry>;\n\t/** {@link Info.plugins}, with the origin of each entry. Same order, same length. */\n\treadonly declared: ReadonlyArray<Declared>;\n\t/**\n\t * Catalog entries from every layer, lowest priority first. Applied over the generated catalog\n\t * in this order, so for one `provider.id` + `id` the last entry wins.\n\t */\n\treadonly models: ReadonlyArray<DeclaredModel>;\n\treadonly model: typeof Model.Type & {\n\t\treadonly provider: string;\n\t\treadonly id: string;\n\t\treadonly thinkingLevel: AikitModel.ThinkingLevel;\n\t\treadonly toolExecution: ToolExecution;\n\t};\n\treadonly retry: RetryPolicy;\n}\n\n/** Let aikit supply model-aware generation defaults. */\nexport const defaults: Info = {\n\tplugins: [],\n\tdeclared: [],\n\tmodels: [],\n\tmodel: {\n\t\tprovider: \"openai\",\n\t\tid: \"gpt-5.6-luna\",\n\t\tthinkingLevel: \"high\",\n\t\ttoolExecution: \"sequential\",\n\t\toptions: { timeoutMs: 3_600_000, maxRetries: 0 },\n\t},\n\tretry: { maxRetries: 3, baseDelayMs: 2_000, maxDelayMs: 60_000 },\n};\n"],"mappings":";;;;AAIA,MAAa,gBAAgB,OAAO,SAAS,OAAO,OAAOA,QAAW,iBAAiB,CAAC;AACxF,MAAa,gBAAgB,OAAO,SAAS,CAAC,cAAc,UAAU,CAAC;AAEvE,MAAM,UAAU,OAAO,OACtB,OAAO,SAAS,OAAO,OAAOA,QAAW,iBAAiB,CAAC,CAAC,QAAQ,UAAU,UAAU,KAAK,CAAC,GAC9F,OAAO,SAAS,OAAO,MAAM,CAC9B;;AAGA,MAAa,gBAAgB;CAC5B,aAAa,OAAO,SAAS,OAAO,MAAM;CAC1C,WAAW,OAAO,SAAS,OAAO,MAAM;CACxC,gBAAgB,OAAO,SAAS,OAAO,SAAS;EAAC;EAAQ;EAAS;CAAM,CAAC,CAAC;CAC1E,SAAS,OAAO,SAAS,OAAO,OAAO,OAAO,QAAQ,OAAO,MAAM,CAAC;CACpE,WAAW,OAAO,SAAS,OAAO,MAAM;CACxC,YAAY,OAAO,SAAS,OAAO,MAAM;CACzC,UAAU,OAAO,SAAS,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO,CAAC;CACtE,iBAAiB,OAAO,SAAS,OAAO;CACxC,SAAS,OAAO,SAAS,OAAO,MAAM;CACtC,QAAQ,OAAO,SAAS,OAAO,SAAS,OAAO,OAAOA,QAAW,aAAa,CAAC,CAAC;AACjF;;;;;AAWA,MAAM,eAAe;AACrB,MAAM,oBAAoB;AAC1B,MAAa,eAAe,OAAO,OAAO,MACzC,OAAO,YAAY,UAAU,aAAa,KAAK,KAAK,KAAK,iBA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O,MAAM,UAAU,CAAC;CAChD,OAAO,OAAO,SAAS,KAAK;AAC7B,CAAC;;AAmED,MAAa,WAAiB;CAC7B,SAAS,CAAC;CACV,UAAU,CAAC;CACX,QAAQ,CAAC;CACT,OAAO;EACN,UAAU;EACV,IAAI;EACJ,eAAe;EACf,eAAe;EACf,SAAS;GAAE,WAAW;GAAW,YAAY;EAAE;CAChD;CACA,OAAO;EAAE,YAAY;EAAG,aAAa;EAAO,YAAY;CAAO;AAChE"}
1
+ {"version":3,"file":"settings.mjs","names":["AikitModel"],"sources":["../../src/settings.ts"],"sourcesContent":["import { Model as AikitModel, type Protocol } from \"@codeworksh/aikit\";\nimport { Effect, Schema, type SchemaAST, SchemaGetter, SchemaIssue } from \"effect\";\nimport { isAikitModelInfo, NonNegativeInt, validateAikitModelInfo } from \"./schema.ts\";\n\nexport const ThinkingLevel = Schema.Literals(Object.values(AikitModel.ThinkingLevelEnum));\nexport const ToolExecution = Schema.Literals([\"sequential\", \"parallel\"]);\nexport type ToolExecution = typeof ToolExecution.Type;\nconst Budgets = Schema.Record(\n\tSchema.Literals(Object.values(AikitModel.ThinkingLevelEnum).filter((level) => level !== \"off\")),\n\tSchema.optional(Schema.Finite),\n);\n\n/** Aikit does not export its request schema; keep this routing surface checked against its public types. */\nexport const requestFields = {\n\ttemperature: Schema.optional(Schema.Finite),\n\tmaxTokens: Schema.optional(Schema.Finite),\n\tcacheRetention: Schema.optional(Schema.Literals([\"none\", \"short\", \"long\"])),\n\theaders: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n\ttimeoutMs: Schema.optional(Schema.Finite),\n\tidleTimeoutMs: Schema.optional(Schema.Finite),\n\tmaxRetries: Schema.optional(Schema.Finite),\n\tmetadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n\tthinkingBudgets: Schema.optional(Budgets),\n\tbaseURL: Schema.optional(Schema.String),\n\tmethod: Schema.optional(Schema.Literals(Object.values(AikitModel.APIMethodEnum))),\n} satisfies Record<\n\t| Exclude<keyof Protocol.CommonOptions, \"signal\" | \"sessionId\" | \"reasoning\" | \"apiKey\" | \"onPayload\">\n\t| \"baseURL\"\n\t| \"method\",\n\tSchema.Top\n>;\n\n/**\n * An API key named, never written: `\"${NAME}\"`, read from the host process environment when the\n * model is called. Settings only ever hold the variable's name.\n */\nconst keyReference = /^\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}$/;\nconst keyReferenceError = 'apiKey must reference an environment variable, e.g. \"${OPENAI_API_KEY}\"';\nexport const KeyReference = Schema.String.check(\n\tSchema.makeFilter((value) => keyReference.test(value) || keyReferenceError),\n);\n\n/** The variable a `\"${NAME}\"` reference names. */\nexport const keyName = (reference: string): string => keyReference.exec(reference)?.[1] ?? reference;\n\nconst reserved = new Set([\n\t\"toolChoice\",\n\t\"activeTools\",\n\t\"provider\",\n\t\"id\",\n\t\"signal\",\n\t\"sessionId\",\n\t\"reasoning\",\n\t\"modelId\",\n\t\"onPayload\",\n\t\"api\",\n\t\"npm\",\n\t\"providerOptionsKey\",\n\t\"compat\",\n\t\"thinkingLevelMap\",\n]);\n\n/** The wire protocol a model speaks, which a catalog entry may have wrong for a local endpoint. */\nexport const ModelProtocol = Schema.Literals(Object.values(AikitModel.KnownProviderEnum));\n\nexport const Block = Schema.StructWithRest(\n\tSchema.Struct({\n\t\t...requestFields,\n\t\tprotocol: Schema.optional(ModelProtocol),\n\t\tthinkingLevel: Schema.optional(ThinkingLevel),\n\t\ttoolExecution: Schema.optional(ToolExecution),\n\t\tcontextWindow: Schema.optional(Schema.Finite),\n\t\t/** Which environment variable holds the key for this model: `\"${NAME}\"`. */\n\t\tapiKey: Schema.optional(KeyReference),\n\t\textras: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n\t}),\n\t[Schema.Record(Schema.String, Schema.Unknown)],\n).check(\n\tSchema.makeFilter(\n\t\t(value) => Object.keys(value).every((key) => !reserved.has(key)) || \"Reserved configuration key in model options\",\n\t),\n);\nexport type Block = typeof Block.Type;\n\nexport const Model = Schema.Struct({\n\tprovider: Schema.optional(Schema.String),\n\tid: Schema.optional(Schema.String),\n\tthinkingLevel: Schema.optional(ThinkingLevel),\n\ttoolExecution: Schema.optional(ToolExecution),\n\tthinkingBudgets: Schema.optional(Budgets),\n\toptions: Schema.optional(Block),\n\tproviderOptions: Schema.optional(Schema.Record(Schema.String, Schema.Record(Schema.String, Block))),\n});\nconst reasonOf = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause));\n\nconst decodeModelEntry = (value: unknown, options: SchemaAST.ParseOptions) =>\n\tEffect.try({\n\t\ttry: () => {\n\t\t\tconst entry = validateAikitModelInfo(value, \"models entry\");\n\t\t\tif (entry.provider.key !== undefined && !keyReference.test(entry.provider.key)) {\n\t\t\t\tthrow new Error(`models entry ${entry.provider.id}/${entry.id}: provider.key: ${keyReferenceError}`);\n\t\t\t}\n\t\t\treturn entry;\n\t\t},\n\t\tcatch: (cause) => new SchemaIssue.InvalidValue({ message: reasonOf(cause) }, value, options),\n\t});\n\n/**\n * A catalog entry in settings: an aikit `Model.Info`, read exactly like an entry of the generated\n * catalog. The one difference is `provider.key`, which must be a `\"${NAME}\"` reference.\n */\nexport const ModelEntry = Schema.Unknown.pipe(\n\tSchema.decodeTo(Schema.declare<AikitModel.Info>(isAikitModelInfo, { expected: \"aikit Model.Info\" }), {\n\t\tdecode: SchemaGetter.transformEffect(decodeModelEntry),\n\t\tencode: SchemaGetter.transformEffect(decodeModelEntry),\n\t}),\n);\nexport type ModelEntry = typeof ModelEntry.Type;\n\n/** A module to load: a path, a `file:` URL, or a package spec. */\nconst PluginReference = Schema.String.check(Schema.isNonEmpty());\n/**\n * Configuration for a plugin something else already selected, named by its ID (`plugin`) or by\n * its registered module string (`package`). It never loads anything: an entry naming a plugin\n * that is not in the selection is ignored.\n */\nconst config = {\n\tenabled: Schema.optional(Schema.Boolean),\n\toptions: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n};\nexport const PluginPatch = Schema.Union(\n\t[Schema.Struct({ plugin: PluginReference, ...config }), Schema.Struct({ package: PluginReference, ...config })],\n\t// `oneOf`, so an entry carrying both keys is a decode failure rather than one of them being\n\t// quietly dropped -- naming a plugin two ways at once says two different things.\n\t{ mode: \"oneOf\" },\n);\nexport const PluginEntry = Schema.Union([PluginReference, PluginPatch]);\nexport type PluginEntry = typeof PluginEntry.Type;\n\n/**\n * Agent-level retry of a turn whose provider request failed transiently (rate limit, overload,\n * 5xx, dropped connection). Delays double from `baseDelayMs` and stop growing at `maxDelayMs`;\n * a server that asks for a longer wait than `maxDelayMs` is not retried. `maxRetries: 0` is off.\n *\n * Separate from `model.options.maxRetries`, which retries inside the provider SDK and defaults to\n * 0 so that the two do not multiply, and so a quota error reaches the loop instead of being retried.\n */\nexport const Retry = Schema.Struct({\n\tmaxRetries: Schema.optional(NonNegativeInt),\n\tbaseDelayMs: Schema.optional(NonNegativeInt),\n\tmaxDelayMs: Schema.optional(NonNegativeInt),\n});\nexport interface RetryPolicy {\n\treadonly maxRetries: number;\n\treadonly baseDelayMs: number;\n\treadonly maxDelayMs: number;\n}\n\nexport const Patch = Schema.Struct({\n\t$schema: Schema.optional(Schema.String),\n\tplugins: Schema.optional(Schema.Array(PluginEntry)),\n\tmodel: Schema.optional(Model),\n\tmodels: Schema.optional(Schema.Array(ModelEntry)),\n\tretry: Schema.optional(Retry),\n});\nexport type Patch = typeof Patch.Type;\n\n/**\n * One plugin entry, and where it came from.\n *\n * Flattening every layer's `plugins` into one array loses the file that declared each entry, and\n * that cannot be recovered afterwards: two layers may declare the same string, so attribution is\n * genuinely gone rather than merely inconvenient. Three things need it -- anchoring a relative\n * path, naming the declaring layer in `plugin list`, and the missing-plugin diagnostic -- so the\n * loaded shape carries it from the start.\n *\n * In simple terms:\n * `written` - is what module the developer is declaring - what\n * `file` - where the module is being declared - where\n * `entry` - the resolved path of the module, relative to the `file`; especially needed for local.\n *\n * Example:\n * written: \"@acme/x@^1\"\n * entry: \"@acme/x@^1\"\n * file: \"/Users/me/.codework/settings.jsonc\"\n *\n * written: \"./plugins/mine.mjs\"\n * entry: \"/Users/me/.codework/plugins/mine.mjs\"\n * file: \"/Users/me/.codework/settings.jsonc\"\n */\nexport interface Declared {\n\t/** The entry exactly as the file spells it, which is the string a person will search for. */\n\treadonly written: PluginEntry;\n\t/** The same entry with any relative path anchored to the directory of its declaring file. */\n\treadonly entry: PluginEntry;\n\t/** The settings file that declared it. */\n\treadonly file: string;\n}\n\n/** A `models` entry, and the settings file that declared it. */\nexport interface DeclaredModel {\n\treadonly entry: AikitModel.Info;\n\treadonly file: string;\n}\n\nexport interface Info {\n\t/**\n\t * Plugin entries added to the harness selection, in order: every layer's entries, lowest\n\t * priority first, so a project's list extends the user's rather than replacing it.\n\t *\n\t * Anchored, and stripped of provenance: this is the list the loader consumes. {@link Info.declared}\n\t * is the same list with the file each entry came from.\n\t */\n\treadonly plugins: ReadonlyArray<PluginEntry>;\n\t/** {@link Info.plugins}, with the origin of each entry. Same order, same length. */\n\treadonly declared: ReadonlyArray<Declared>;\n\t/**\n\t * Catalog entries from every layer, lowest priority first. Applied over the generated catalog\n\t * in this order, so for one `provider.id` + `id` the last entry wins.\n\t */\n\treadonly models: ReadonlyArray<DeclaredModel>;\n\treadonly model: typeof Model.Type & {\n\t\treadonly provider: string;\n\t\treadonly id: string;\n\t\treadonly thinkingLevel: AikitModel.ThinkingLevel;\n\t\treadonly toolExecution: ToolExecution;\n\t};\n\treadonly retry: RetryPolicy;\n}\n\n/** Let aikit supply model-aware generation defaults. */\nexport const defaults: Info = {\n\tplugins: [],\n\tdeclared: [],\n\tmodels: [],\n\tmodel: {\n\t\tprovider: \"openai\",\n\t\tid: \"gpt-5.6-luna\",\n\t\tthinkingLevel: \"high\",\n\t\ttoolExecution: \"sequential\",\n\t\toptions: { timeoutMs: 3_600_000, idleTimeoutMs: 300_000, maxRetries: 0 },\n\t},\n\tretry: { maxRetries: 3, baseDelayMs: 2_000, maxDelayMs: 60_000 },\n};\n"],"mappings":";;;;AA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AE,YAAY;EAAG,aAAa;EAAO,YAAY;CAAO;AAChE"}
@@ -1,2 +1,2 @@
1
- import { _ as IToolProgress, b as make, v as ToolProgress, x as noop, y as ToolProgressPartial } from "../tool-DuYBgiJf.mjs";
1
+ import { _ as IToolProgress, b as make, v as ToolProgress, x as noop, y as ToolProgressPartial } from "../tool-_ajVYIY5.mjs";
2
2
  export { IToolProgress, ToolProgress, ToolProgressPartial, make, noop };
@@ -1,4 +1,4 @@
1
- import { a as RegisteredTool, i as ModelContent, t as AnyToolDef } from "./tool-DuYBgiJf.mjs";
1
+ import { a as RegisteredTool, i as ModelContent, t as AnyToolDef } from "./tool-_ajVYIY5.mjs";
2
2
  import { Effect, Schema } from "effect";
3
3
  declare namespace tool_d_exports {
4
4
  export { HookReturn, ToolAddOptions, ToolAfter, ToolAfterFn, ToolAfterResult, ToolBefore, ToolBeforeFn, ToolBeforeResult, ToolDefPatch, ToolRegistration, ToolRegistry, ToolResultContent };
@@ -284,4 +284,4 @@ interface ToolRegistry {
284
284
  }
285
285
  //#endregion
286
286
  export { ToolAfterResult as a, ToolBeforeResult as c, ToolRegistry as d, ToolResultContent as f, ToolAfterFn as i, ToolDefPatch as l, ToolAddOptions as n, ToolBefore as o, tool_d_exports as p, ToolAfter as r, ToolBeforeFn as s, HookReturn as t, ToolRegistration as u };
287
- //# sourceMappingURL=tool-BoVqkYvL.d.mts.map
287
+ //# sourceMappingURL=tool-D4_I_rzy.d.mts.map
@@ -68,7 +68,17 @@ interface ToolDef<Name extends string = string, Params extends Schema.Top = Sche
68
68
  readonly promptSnippet?: string;
69
69
  /** Optional guideline bullets appended to the default system prompt Guidelines section when this tool is active. */
70
70
  readonly promptGuidelines?: ReadonlyArray<string>;
71
+ /**
72
+ * Repair argument shapes models commonly send before they are validated against
73
+ * `parameters`. Return a copy; a throw makes the arguments invalid.
74
+ */
75
+ readonly prepareArguments?: (args: unknown) => unknown;
71
76
  readonly parameters: Params;
77
+ /**
78
+ * How the provider constrains the generated arguments. `{ type: "json_schema", strict: "prefer" }` sends
79
+ * `parameters` in strict mode where the provider can express it and falls back to non-strict otherwise.
80
+ */
81
+ readonly constrainedSampling?: Message.Tool["constrainedSampling"];
72
82
  readonly success: Success;
73
83
  /** Declared, model-visible failures (typed). Omit for tools that cannot fail expectedly. */
74
84
  readonly failure?: Failure;
@@ -76,6 +86,11 @@ interface ToolDef<Name extends string = string, Params extends Schema.Top = Sche
76
86
  readonly encodeContent?: (success: Success["Type"]) => ModelContent;
77
87
  /** Render an expected failure for the model. Omit → executor falls back to JSON text. */
78
88
  readonly encodeFailureContent?: (failure: Failure["Type"]) => ModelContent;
89
+ /**
90
+ * The `details` kept with a success, for UIs and programmatic consumers. Omit → the encoded
91
+ * success. Set it when `encodeContent` already carries the payload, so it is not stored twice.
92
+ */
93
+ readonly encodeDetails?: (success: Success["Type"]) => unknown;
79
94
  }
80
95
  /** A handler: validated params + context → typed success or typed failure. */
81
96
  type Handler<Params extends Schema.Top, Success extends Schema.Top, Failure extends Schema.Top, R = never> = (params: Params["Type"], ctx: ToolCallContext) => Effect.Effect<Success["Type"], Failure["Type"], R>;
@@ -91,11 +106,15 @@ interface DefineInput<Name extends string, Params extends Schema.Top, Success ex
91
106
  readonly description: string;
92
107
  readonly label?: string;
93
108
  readonly promptSnippet?: string;
109
+ readonly promptGuidelines?: ReadonlyArray<string>;
110
+ readonly prepareArguments?: (args: unknown) => unknown;
94
111
  readonly parameters: Params;
112
+ readonly constrainedSampling?: Message.Tool["constrainedSampling"];
95
113
  readonly success: Success;
96
114
  readonly failure?: Failure;
97
115
  readonly encodeContent?: (success: Success["Type"]) => ModelContent;
98
116
  readonly encodeFailureContent?: (failure: Failure["Type"]) => ModelContent;
117
+ readonly encodeDetails?: (success: Success["Type"]) => unknown;
99
118
  }
100
119
  /** Define a pure tool (handler attached later via {@link implement} or a toolkit). */
101
120
  declare const define: <Name extends string, Params extends Schema.Top, Success extends Schema.Top, Failure extends Schema.Top = Schema.Top>(input: DefineInput<Name, Params, Success, Failure>) => ToolDef<Name, Params, Success, Failure>;
@@ -139,4 +158,4 @@ declare const toProviderJsonSchema: (schema: Schema.Top) => Record<string, unkno
139
158
  declare const toAikitTool: (def: AnyToolDef) => Message.Tool;
140
159
  //#endregion
141
160
  export { IToolProgress as _, RegisteredTool as a, make$1 as b, ToolImpl as c, make as d, provide as f, tool_d_exports as g, toProviderJsonSchema as h, ModelContent as i, define as l, toAikitTool as m, AnyToolImpl as n, ToolCallContext as o, register as p, Handler as r, ToolDef as s, AnyToolDef as t, implement as u, ToolProgress as v, noop as x, ToolProgressPartial as y };
142
- //# sourceMappingURL=tool-DuYBgiJf.d.mts.map
161
+ //# sourceMappingURL=tool-_ajVYIY5.d.mts.map
package/tool.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as RegisteredTool, c as ToolImpl, d as make, f as provide, h as toProviderJsonSchema, i as ModelContent, l as define, m as toAikitTool, n as AnyToolImpl, o as ToolCallContext, p as register, r as Handler, s as ToolDef, t as AnyToolDef, u as implement } from "./tool-DuYBgiJf.mjs";
1
+ import { a as RegisteredTool, c as ToolImpl, d as make, f as provide, h as toProviderJsonSchema, i as ModelContent, l as define, m as toAikitTool, n as AnyToolImpl, o as ToolCallContext, p as register, r as Handler, s as ToolDef, t as AnyToolDef, u as implement } from "./tool-_ajVYIY5.mjs";
2
2
  export { AnyToolDef, AnyToolImpl, Handler, ModelContent, RegisteredTool, ToolCallContext, ToolDef, ToolImpl, define, implement, make, provide, register, toAikitTool, toProviderJsonSchema };
package/tool.mjs CHANGED
@@ -63,7 +63,8 @@ const toProviderJsonSchema = (schema) => Schema.toStandardJSONSchemaV1(schema)["
63
63
  const toAikitTool = (def) => ({
64
64
  name: def.name,
65
65
  description: def.description,
66
- parameters: toProviderJsonSchema(def.parameters)
66
+ parameters: toProviderJsonSchema(def.parameters),
67
+ ...def.constrainedSampling === void 0 ? {} : { constrainedSampling: def.constrainedSampling }
67
68
  });
68
69
  //#endregion
69
70
  export { ToolCallContext, define, implement, make, provide, register, tool_exports as t, toAikitTool, toProviderJsonSchema };
package/tool.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"tool.mjs","names":[],"sources":["../../src/tool.ts"],"sourcesContent":["import type { Message } from \"@codeworksh/aikit\";\nimport { Effect, type Layer, Schema } from \"effect\";\nimport type { TSchema } from \"typebox\";\nimport { ToolExecutionError } from \"./tool/error.ts\";\nimport type { ToolProgress } from \"./tool/progress.ts\";\n\n/**\n * The tool definition + handler model.\n *\n * A tool definition is pure, serializable data: name, description, and Effect\n * Schema for parameters / success / failure. Execution is a separate `Handler`\n * — an `Effect` whose capability dependencies (e.g. `ToolShell`) live in its\n * requirements `R`, provided by a Layer at runtime. Separating the two is the\n * main testing win: assert on the definition as plain data, and run the handler\n * against a stub capability Layer.\n *\n * Effect Schema is the single source of truth. {@link toAikitTool} derives a\n * provider-safe JSON Schema object for the aikit wire view; the harness\n * decode/encodes arguments and results with Effect Schema natively (it does not\n * use aikit's Typebox validators).\n */\n\n/** What the model reads next turn (the `content` side of content/details). */\nexport type ModelContent = ReadonlyArray<Message.TextContent | Message.ImageContent>;\n\n/** Per-call metadata handed to a handler instead of positional args. */\nexport const ToolCallContext = Schema.Struct({\n\tcallID: Schema.String,\n\ttoolName: Schema.String,\n\trawArgs: Schema.Record(Schema.String, Schema.Unknown),\n});\nexport type ToolCallContext = typeof ToolCallContext.Type;\n\n/**\n * A pure tool definition. Parametrised over the *schema* instances so the\n * decoded parameter/success/failure types can be recovered via `[\"Type\"]`.\n */\nexport interface ToolDef<\n\tName extends string = string,\n\tParams extends Schema.Top = Schema.Top,\n\tSuccess extends Schema.Top = Schema.Top,\n\tFailure extends Schema.Top = Schema.Top,\n> {\n\treadonly name: Name;\n\treadonly description: string;\n\t/** Human-readable display label (kept from the previous `AgentTool`). */\n\treadonly label?: string;\n\t/**\n\t * A short one-line summary for compact tool listings (e.g. a system-prompt tool index),\n\t * distinct from the fuller `description`.\n\t */\n\treadonly promptSnippet?: string;\n\t/** Optional guideline bullets appended to the default system prompt Guidelines section when this tool is active. */\n\treadonly promptGuidelines?: ReadonlyArray<string>;\n\treadonly parameters: Params;\n\treadonly success: Success;\n\t/** Declared, model-visible failures (typed). Omit for tools that cannot fail expectedly. */\n\treadonly failure?: Failure;\n\t/** Render success for the model. Omit → executor falls back to JSON text. */\n\treadonly encodeContent?: (success: Success[\"Type\"]) => ModelContent;\n\t/** Render an expected failure for the model. Omit → executor falls back to JSON text. */\n\treadonly encodeFailureContent?: (failure: Failure[\"Type\"]) => ModelContent;\n}\n\n/** A handler: validated params + context → typed success or typed failure. */\nexport type Handler<Params extends Schema.Top, Success extends Schema.Top, Failure extends Schema.Top, R = never> = (\n\tparams: Params[\"Type\"],\n\tctx: ToolCallContext,\n) => Effect.Effect<Success[\"Type\"], Failure[\"Type\"], R>;\n\n/** A definition paired with its handler (the unit the executor runs). */\nexport interface ToolImpl<\n\tName extends string = string,\n\tParams extends Schema.Top = Schema.Top,\n\tSuccess extends Schema.Top = Schema.Top,\n\tFailure extends Schema.Top = Schema.Top,\n\tR = never,\n> {\n\treadonly definition: ToolDef<Name, Params, Success, Failure>;\n\treadonly handler: Handler<Params, Success, Failure, R>;\n}\n\n// Heterogeneous-collection aliases. `any` for the schema generics keeps handlers\n// of differing parameter types assignable into one array (the precise generics\n// live on the authoring helpers below).\n// biome-ignore lint/suspicious/noExplicitAny: erased schema generics for storage\nexport type AnyToolDef = ToolDef<string, any, any, any>;\n// biome-ignore lint/suspicious/noExplicitAny: erased schema generics for storage\nexport type AnyToolImpl<R = never> = ToolImpl<string, any, any, any, R>;\n\ninterface DefineInput<\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top,\n> {\n\treadonly name: Name;\n\treadonly description: string;\n\treadonly label?: string;\n\treadonly promptSnippet?: string;\n\treadonly parameters: Params;\n\treadonly success: Success;\n\treadonly failure?: Failure;\n\treadonly encodeContent?: (success: Success[\"Type\"]) => ModelContent;\n\treadonly encodeFailureContent?: (failure: Failure[\"Type\"]) => ModelContent;\n}\n\n/** Define a pure tool (handler attached later via {@link implement} or a toolkit). */\nexport const define = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top = Schema.Top,\n>(\n\tinput: DefineInput<Name, Params, Success, Failure>,\n): ToolDef<Name, Params, Success, Failure> => ({\n\t...input,\n});\n\n/** Attach a handler to an existing definition (the testable def/exec split). */\nexport const implement = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top,\n\tR = never,\n>(\n\tdefinition: ToolDef<Name, Params, Success, Failure>,\n\thandler: Handler<Params, Success, Failure, R>,\n): ToolImpl<Name, Params, Success, Failure, R> => ({ definition, handler });\n\n/** Sugar for the co-located case: a definition with its handler in one object. */\nexport const make = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top = Schema.Top,\n\tR = never,\n>(\n\tinput: DefineInput<Name, Params, Success, Failure> & {\n\t\treadonly handler: Handler<Params, Success, Failure, R>;\n\t},\n): ToolImpl<Name, Params, Success, Failure, R> => {\n\tconst { handler, ...rest } = input;\n\treturn { definition: define(rest), handler };\n};\n\n/**\n * A tool ready to register: its capability requirements have been discharged, leaving only\n * the executor-provided {@link ToolProgress}. The registry and executor hold `RegisteredTool`s\n * and are non-generic (only `handle` is generic, over a progress sink's `RProgress`), so any\n * number of tools — built-in or\n * third-party/plugin — compose without a shared capability union\n */\nexport interface RegisteredTool {\n\treadonly definition: AnyToolDef;\n\treadonly handler: (\n\t\tparams: unknown,\n\t\tctx: ToolCallContext,\n\t) => Effect.Effect<unknown, ToolExecutionError, ToolProgress>;\n}\n\nconst toRegistered = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top,\n>(\n\tdefinition: ToolDef<Name, Params, Success, Failure>,\n\thandler: Handler<Params, Success, Failure, ToolProgress>,\n): RegisteredTool => ({\n\tdefinition,\n\t// The executor decodes with `definition.parameters` before invoking this\n\t// erased handler, so restoring the authored parameter type is safe here.\n\thandler: (params, ctx) =>\n\t\thandler(params as Params[\"Type\"], ctx).pipe(\n\t\t\tEffect.mapError((cause) => new ToolExecutionError({ toolName: definition.name, cause })),\n\t\t),\n});\n\n/** Register a tool whose only requirement is the executor-provided progress service. */\nexport const register = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top,\n>(\n\timpl: ToolImpl<Name, Params, Success, Failure, ToolProgress>,\n): RegisteredTool => toRegistered(impl.definition, impl.handler);\n\n/**\n * Discharge a tool's capability requirements into a {@link RegisteredTool}, erasing its `R`\n * (the executor still provides `ToolProgress`). This is the registration boundary: a\n * plugin/third-party tool provides its own fully-resolved capability Layer here, so the\n * registry never has to unify anyone's `R`.\n */\nexport const provide = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top,\n\tR,\n>(\n\timpl: ToolImpl<Name, Params, Success, Failure, R | ToolProgress>,\n\tlayer: Layer.Layer<R>,\n): RegisteredTool =>\n\t// `Effect.provide` discharges `R`, leaving `ToolProgress`. TS can't simplify\n\t// `Exclude<ToolProgress, R>` for a generic `R`, so localize the cast before\n\t// crossing the registered-tool boundary.\n\ttoRegistered(impl.definition, ((params, ctx) => impl.handler(params, ctx).pipe(Effect.provide(layer))) as Handler<\n\t\tParams,\n\t\tSuccess,\n\t\tFailure,\n\t\tToolProgress\n\t>);\n\n/**\n * Derive a provider-safe JSON Schema object from an Effect Schema. This is the\n * single boundary that crosses into the provider wire; if a provider rejects a\n * construct, fix it here. Draft-07 inlines the root (no top-level `$ref`).\n */\nexport const toProviderJsonSchema = (schema: Schema.Top): Record<string, unknown> =>\n\tSchema.toStandardJSONSchemaV1(schema)[\"~standard\"].jsonSchema.input({ target: \"draft-07\" });\n\n/**\n * Build the aikit `Message.Tool` wire view from a definition. The derived JSON\n * Schema object satisfies aikit's `parameters` slot structurally at runtime; the\n * single localized cast keeps aikit untouched (decision 3-A).\n */\nexport const toAikitTool = (def: AnyToolDef): Message.Tool => ({\n\tname: def.name,\n\tdescription: def.description,\n\tparameters: toProviderJsonSchema(def.parameters) as unknown as TSchema,\n});\n"],"mappings":";;;;;;;;;;;;;;;AA0BA,MAAa,kBAAkB,OAAO,OAAO;CAC5C,QAAQ,OAAO;CACf,UAAU,OAAO;CACjB,SAAS,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;AACrD,CAAC;;AA8ED,MAAa,UAMZ,WAC8C,EAC9C,GAAG,MACJ;;AAGA,MAAa,aAOZ,YACA,aACkD;CAAE;CAAY;AAAQ;;AAGzE,MAAa,QAOZ,UAGiD;CACjD,MAAM,EAAE,SAAS,GAAG,SAAS;CAC7B,OAAO;EAAE,YAAY,OAAO,IAAI;EAAG;CAAQ;AAC5C;AAiBA,MAAM,gBAML,YACA,aACqB;CACrB;CAGA,UAAU,QAAQ,QACjB,QAAQ,QAA0B,GAAG,CAAC,CAAC,KACtC,OAAO,UAAU,UAAU,IAAI,mBAAmB;EAAE,UAAU,WAAW;EAAM;CAAM,CAAC,CAAC,CACxF;AACF;;AAGA,MAAa,YAMZ,SACoB,aAAa,KAAK,YAAY,KAAK,OAAO;;;;;;;AAQ/D,MAAa,WAOZ,MACA,UAKA,aAAa,KAAK,cAAc,QAAQ,QAAQ,KAAK,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK,OAAO,QAAQ,KAAK,CAAC,EAKnG;;;;;;AAOF,MAAa,wBAAwB,WACpC,OAAO,uBAAuB,MAAM,CAAC,CAAC,YAAY,CAAC,WAAW,MAAM,EAAE,QAAQ,WAAW,CAAC;;;;;;AAO3F,MAAa,eAAe,SAAmC;CAC9D,MAAM,IAAI;CACV,aAAa,IAAI;CACjB,YAAY,qBAAqB,IAAI,UAAU;AAChD"}
1
+ {"version":3,"file":"tool.mjs","names":[],"sources":["../../src/tool.ts"],"sourcesContent":["import type { Message } from \"@codeworksh/aikit\";\nimport { Effect, type Layer, Schema } from \"effect\";\nimport type { TSchema } from \"typebox\";\nimport { ToolExecutionError } from \"./tool/error.ts\";\nimport type { ToolProgress } from \"./tool/progress.ts\";\n\n/**\n * The tool definition + handler model.\n *\n * A tool definition is pure, serializable data: name, description, and Effect\n * Schema for parameters / success / failure. Execution is a separate `Handler`\n * — an `Effect` whose capability dependencies (e.g. `ToolShell`) live in its\n * requirements `R`, provided by a Layer at runtime. Separating the two is the\n * main testing win: assert on the definition as plain data, and run the handler\n * against a stub capability Layer.\n *\n * Effect Schema is the single source of truth. {@link toAikitTool} derives a\n * provider-safe JSON Schema object for the aikit wire view; the harness\n * decode/encodes arguments and results with Effect Schema natively (it does not\n * use aikit's Typebox validators).\n */\n\n/** What the model reads next turn (the `content` side of content/details). */\nexport type ModelContent = ReadonlyArray<Message.TextContent | Message.ImageContent>;\n\n/** Per-call metadata handed to a handler instead of positional args. */\nexport const ToolCallContext = Schema.Struct({\n\tcallID: Schema.String,\n\ttoolName: Schema.String,\n\trawArgs: Schema.Record(Schema.String, Schema.Unknown),\n});\nexport type ToolCallContext = typeof ToolCallContext.Type;\n\n/**\n * A pure tool definition. Parametrised over the *schema* instances so the\n * decoded parameter/success/failure types can be recovered via `[\"Type\"]`.\n */\nexport interface ToolDef<\n\tName extends string = string,\n\tParams extends Schema.Top = Schema.Top,\n\tSuccess extends Schema.Top = Schema.Top,\n\tFailure extends Schema.Top = Schema.Top,\n> {\n\treadonly name: Name;\n\treadonly description: string;\n\t/** Human-readable display label (kept from the previous `AgentTool`). */\n\treadonly label?: string;\n\t/**\n\t * A short one-line summary for compact tool listings (e.g. a system-prompt tool index),\n\t * distinct from the fuller `description`.\n\t */\n\treadonly promptSnippet?: string;\n\t/** Optional guideline bullets appended to the default system prompt Guidelines section when this tool is active. */\n\treadonly promptGuidelines?: ReadonlyArray<string>;\n\t/**\n\t * Repair argument shapes models commonly send before they are validated against\n\t * `parameters`. Return a copy; a throw makes the arguments invalid.\n\t */\n\treadonly prepareArguments?: (args: unknown) => unknown;\n\treadonly parameters: Params;\n\t/**\n\t * How the provider constrains the generated arguments. `{ type: \"json_schema\", strict: \"prefer\" }` sends\n\t * `parameters` in strict mode where the provider can express it and falls back to non-strict otherwise.\n\t */\n\treadonly constrainedSampling?: Message.Tool[\"constrainedSampling\"];\n\treadonly success: Success;\n\t/** Declared, model-visible failures (typed). Omit for tools that cannot fail expectedly. */\n\treadonly failure?: Failure;\n\t/** Render success for the model. Omit → executor falls back to JSON text. */\n\treadonly encodeContent?: (success: Success[\"Type\"]) => ModelContent;\n\t/** Render an expected failure for the model. Omit → executor falls back to JSON text. */\n\treadonly encodeFailureContent?: (failure: Failure[\"Type\"]) => ModelContent;\n\t/**\n\t * The `details` kept with a success, for UIs and programmatic consumers. Omit → the encoded\n\t * success. Set it when `encodeContent` already carries the payload, so it is not stored twice.\n\t */\n\treadonly encodeDetails?: (success: Success[\"Type\"]) => unknown;\n}\n\n/** A handler: validated params + context → typed success or typed failure. */\nexport type Handler<Params extends Schema.Top, Success extends Schema.Top, Failure extends Schema.Top, R = never> = (\n\tparams: Params[\"Type\"],\n\tctx: ToolCallContext,\n) => Effect.Effect<Success[\"Type\"], Failure[\"Type\"], R>;\n\n/** A definition paired with its handler (the unit the executor runs). */\nexport interface ToolImpl<\n\tName extends string = string,\n\tParams extends Schema.Top = Schema.Top,\n\tSuccess extends Schema.Top = Schema.Top,\n\tFailure extends Schema.Top = Schema.Top,\n\tR = never,\n> {\n\treadonly definition: ToolDef<Name, Params, Success, Failure>;\n\treadonly handler: Handler<Params, Success, Failure, R>;\n}\n\n// Heterogeneous-collection aliases. `any` for the schema generics keeps handlers\n// of differing parameter types assignable into one array (the precise generics\n// live on the authoring helpers below).\n// biome-ignore lint/suspicious/noExplicitAny: erased schema generics for storage\nexport type AnyToolDef = ToolDef<string, any, any, any>;\n// biome-ignore lint/suspicious/noExplicitAny: erased schema generics for storage\nexport type AnyToolImpl<R = never> = ToolImpl<string, any, any, any, R>;\n\ninterface DefineInput<\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top,\n> {\n\treadonly name: Name;\n\treadonly description: string;\n\treadonly label?: string;\n\treadonly promptSnippet?: string;\n\treadonly promptGuidelines?: ReadonlyArray<string>;\n\treadonly prepareArguments?: (args: unknown) => unknown;\n\treadonly parameters: Params;\n\treadonly constrainedSampling?: Message.Tool[\"constrainedSampling\"];\n\treadonly success: Success;\n\treadonly failure?: Failure;\n\treadonly encodeContent?: (success: Success[\"Type\"]) => ModelContent;\n\treadonly encodeFailureContent?: (failure: Failure[\"Type\"]) => ModelContent;\n\treadonly encodeDetails?: (success: Success[\"Type\"]) => unknown;\n}\n\n/** Define a pure tool (handler attached later via {@link implement} or a toolkit). */\nexport const define = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top = Schema.Top,\n>(\n\tinput: DefineInput<Name, Params, Success, Failure>,\n): ToolDef<Name, Params, Success, Failure> => ({\n\t...input,\n});\n\n/** Attach a handler to an existing definition (the testable def/exec split). */\nexport const implement = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top,\n\tR = never,\n>(\n\tdefinition: ToolDef<Name, Params, Success, Failure>,\n\thandler: Handler<Params, Success, Failure, R>,\n): ToolImpl<Name, Params, Success, Failure, R> => ({ definition, handler });\n\n/** Sugar for the co-located case: a definition with its handler in one object. */\nexport const make = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top = Schema.Top,\n\tR = never,\n>(\n\tinput: DefineInput<Name, Params, Success, Failure> & {\n\t\treadonly handler: Handler<Params, Success, Failure, R>;\n\t},\n): ToolImpl<Name, Params, Success, Failure, R> => {\n\tconst { handler, ...rest } = input;\n\treturn { definition: define(rest), handler };\n};\n\n/**\n * A tool ready to register: its capability requirements have been discharged, leaving only\n * the executor-provided {@link ToolProgress}. The registry and executor hold `RegisteredTool`s\n * and are non-generic (only `handle` is generic, over a progress sink's `RProgress`), so any\n * number of tools — built-in or\n * third-party/plugin — compose without a shared capability union\n */\nexport interface RegisteredTool {\n\treadonly definition: AnyToolDef;\n\treadonly handler: (\n\t\tparams: unknown,\n\t\tctx: ToolCallContext,\n\t) => Effect.Effect<unknown, ToolExecutionError, ToolProgress>;\n}\n\nconst toRegistered = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top,\n>(\n\tdefinition: ToolDef<Name, Params, Success, Failure>,\n\thandler: Handler<Params, Success, Failure, ToolProgress>,\n): RegisteredTool => ({\n\tdefinition,\n\t// The executor decodes with `definition.parameters` before invoking this\n\t// erased handler, so restoring the authored parameter type is safe here.\n\thandler: (params, ctx) =>\n\t\thandler(params as Params[\"Type\"], ctx).pipe(\n\t\t\tEffect.mapError((cause) => new ToolExecutionError({ toolName: definition.name, cause })),\n\t\t),\n});\n\n/** Register a tool whose only requirement is the executor-provided progress service. */\nexport const register = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top,\n>(\n\timpl: ToolImpl<Name, Params, Success, Failure, ToolProgress>,\n): RegisteredTool => toRegistered(impl.definition, impl.handler);\n\n/**\n * Discharge a tool's capability requirements into a {@link RegisteredTool}, erasing its `R`\n * (the executor still provides `ToolProgress`). This is the registration boundary: a\n * plugin/third-party tool provides its own fully-resolved capability Layer here, so the\n * registry never has to unify anyone's `R`.\n */\nexport const provide = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top,\n\tR,\n>(\n\timpl: ToolImpl<Name, Params, Success, Failure, R | ToolProgress>,\n\tlayer: Layer.Layer<R>,\n): RegisteredTool =>\n\t// `Effect.provide` discharges `R`, leaving `ToolProgress`. TS can't simplify\n\t// `Exclude<ToolProgress, R>` for a generic `R`, so localize the cast before\n\t// crossing the registered-tool boundary.\n\ttoRegistered(impl.definition, ((params, ctx) => impl.handler(params, ctx).pipe(Effect.provide(layer))) as Handler<\n\t\tParams,\n\t\tSuccess,\n\t\tFailure,\n\t\tToolProgress\n\t>);\n\n/**\n * Derive a provider-safe JSON Schema object from an Effect Schema. This is the\n * single boundary that crosses into the provider wire; if a provider rejects a\n * construct, fix it here. Draft-07 inlines the root (no top-level `$ref`).\n */\nexport const toProviderJsonSchema = (schema: Schema.Top): Record<string, unknown> =>\n\tSchema.toStandardJSONSchemaV1(schema)[\"~standard\"].jsonSchema.input({ target: \"draft-07\" });\n\n/**\n * Build the aikit `Message.Tool` wire view from a definition. The derived JSON\n * Schema object satisfies aikit's `parameters` slot structurally at runtime; the\n * single localized cast keeps aikit untouched (decision 3-A).\n */\nexport const toAikitTool = (def: AnyToolDef): Message.Tool => ({\n\tname: def.name,\n\tdescription: def.description,\n\tparameters: toProviderJsonSchema(def.parameters) as unknown as TSchema,\n\t...(def.constrainedSampling === undefined ? {} : { constrainedSampling: def.constrainedSampling }),\n});\n"],"mappings":";;;;;;;;;;;;;;;AA0BA,MAAa,kBAAkB,OAAO,OAAO;CAC5C,QAAQ,OAAO;CACf,UAAU,OAAO;CACjB,SAAS,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;AACrD,CAAC;;AAiGD,MAAa,UAMZ,WAC8C,EAC9C,GAAG,MACJ;;AAGA,MAAa,aAOZ,YACA,aACkD;CAAE;CAAY;AAAQ;;AAGzE,MAAa,QAOZ,UAGiD;CACjD,MAAM,EAAE,SAAS,GAAG,SAAS;CAC7B,OAAO;EAAE,YAAY,OAAO,IAAI;EAAG;CAAQ;AAC5C;AAiBA,MAAM,gBAML,YACA,aACqB;CACrB;CAGA,UAAU,QAAQ,QACjB,QAAQ,QAA0B,GAAG,CAAC,CAAC,KACtC,OAAO,UAAU,UAAU,IAAI,mBAAmB;EAAE,UAAU,WAAW;EAAM;CAAM,CAAC,CAAC,CACxF;AACF;;AAGA,MAAa,YAMZ,SACoB,aAAa,KAAK,YAAY,KAAK,OAAO;;;;;;;AAQ/D,MAAa,WAOZ,MACA,UAKA,aAAa,KAAK,cAAc,QAAQ,QAAQ,KAAK,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK,OAAO,QAAQ,KAAK,CAAC,EAKnG;;;;;;AAOF,MAAa,wBAAwB,WACpC,OAAO,uBAAuB,MAAM,CAAC,CAAC,YAAY,CAAC,WAAW,MAAM,EAAE,QAAQ,WAAW,CAAC;;;;;;AAO3F,MAAa,eAAe,SAAmC;CAC9D,MAAM,IAAI;CACV,aAAa,IAAI;CACjB,YAAY,qBAAqB,IAAI,UAAU;CAC/C,GAAI,IAAI,wBAAwB,KAAA,IAAY,CAAC,IAAI,EAAE,qBAAqB,IAAI,oBAAoB;AACjG"}