@spellkave/tool-runtime 0.0.0-stage → 0.1.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/LICENSE +89 -0
- package/package.json +30 -4
- package/src/capabilities.ts +74 -0
- package/src/index.ts +4 -0
- package/src/runtime.ts +278 -0
- package/src/world-deltas.ts +222 -0
- package/src/world-events.ts +27 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# PolyForm Shield License 1.0.0
|
|
2
|
+
|
|
3
|
+
<https://polyformproject.org/licenses/shield/1.0.0>
|
|
4
|
+
|
|
5
|
+
## Acceptance
|
|
6
|
+
|
|
7
|
+
In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
|
|
8
|
+
|
|
9
|
+
## Copyright License
|
|
10
|
+
|
|
11
|
+
The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
|
|
12
|
+
|
|
13
|
+
## Distribution License
|
|
14
|
+
|
|
15
|
+
The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
|
|
16
|
+
|
|
17
|
+
## Notices
|
|
18
|
+
|
|
19
|
+
You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
|
|
20
|
+
|
|
21
|
+
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
|
|
22
|
+
|
|
23
|
+
## Changes and New Works License
|
|
24
|
+
|
|
25
|
+
The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
|
|
26
|
+
|
|
27
|
+
## Patent License
|
|
28
|
+
|
|
29
|
+
The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
|
|
30
|
+
|
|
31
|
+
## Noncompete
|
|
32
|
+
|
|
33
|
+
Any purpose is a permitted purpose, except for providing any product that competes with the software or any product the licensor or any of its affiliates provides using the software.
|
|
34
|
+
|
|
35
|
+
## Competition
|
|
36
|
+
|
|
37
|
+
Goods and services compete even when they provide functionality through different kinds of interfaces or for different technical platforms. Applications can compete with services, libraries with plugins, frameworks with development tools, and so on, even if they're written in different programming languages or for different computer architectures. Goods and services compete even when provided free of charge. If you market a product as a practical substitute for the software or another product, it definitely competes.
|
|
38
|
+
|
|
39
|
+
## New Products
|
|
40
|
+
|
|
41
|
+
If you are using the software to provide a product that does not compete, but the licensor or any of its affiliates brings your product into competition by providing a new version of the software or another product using the software, you may continue using versions of the software available under these terms beforehand to provide your competing product, but not any later versions.
|
|
42
|
+
|
|
43
|
+
## Discontinued Products
|
|
44
|
+
|
|
45
|
+
You may begin using the software to compete with a product or service that the licensor or any of its affiliates has stopped providing, unless the licensor includes a plain-text line beginning with `Licensor Line of Business:` with the software that mentions that line of business. For example:
|
|
46
|
+
|
|
47
|
+
> Licensor Line of Business: YoyodyneCMS Content Management System (http://example.com/cms)
|
|
48
|
+
|
|
49
|
+
## Sales of Business
|
|
50
|
+
|
|
51
|
+
If the licensor or any of its affiliates sells a line of business developing the software or using the software to provide a product, the buyer can also enforce [Noncompete](#noncompete) for that product.
|
|
52
|
+
|
|
53
|
+
## Fair Use
|
|
54
|
+
|
|
55
|
+
You may have "fair use" rights for the software under the law. These terms do not limit them.
|
|
56
|
+
|
|
57
|
+
## No Other Rights
|
|
58
|
+
|
|
59
|
+
These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
|
|
60
|
+
|
|
61
|
+
## Patent Defense
|
|
62
|
+
|
|
63
|
+
If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
|
|
64
|
+
|
|
65
|
+
## Violations
|
|
66
|
+
|
|
67
|
+
The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
|
|
68
|
+
|
|
69
|
+
## No Liability
|
|
70
|
+
|
|
71
|
+
***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
|
|
72
|
+
|
|
73
|
+
## Definitions
|
|
74
|
+
|
|
75
|
+
The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
|
|
76
|
+
|
|
77
|
+
A **product** can be a good or service, or a combination of them.
|
|
78
|
+
|
|
79
|
+
**You** refers to the individual or entity agreeing to these terms.
|
|
80
|
+
|
|
81
|
+
**Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all its affiliates.
|
|
82
|
+
|
|
83
|
+
**Affiliates** means the other organizations than an organization has control over, is under the control of, or is under common control with.
|
|
84
|
+
|
|
85
|
+
**Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
|
|
86
|
+
|
|
87
|
+
**Your licenses** are all the licenses granted to you for the software under these terms.
|
|
88
|
+
|
|
89
|
+
**Use** means anything you do with the software requiring one of your licenses.
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spellkave/tool-runtime",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Browser-safe transport-neutral binding, validation, dispatch, result shaping, and capability-port coordination for Spellkave tool contracts.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.ts",
|
|
7
|
+
"types": "./src/index.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./src/index.ts",
|
|
11
|
+
"default": "./src/index.ts"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"src"
|
|
16
|
+
],
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@spellkave/tool-contracts": "0.1.0",
|
|
19
|
+
"@spellkave/world-events": "0.1.0",
|
|
20
|
+
"typebox": "1.1.38"
|
|
21
|
+
},
|
|
22
|
+
"license": "PolyForm-Shield-1.0.0",
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/b4mad-technologies/sk-sdk.git",
|
|
26
|
+
"directory": "packages/spellkave-tool-runtime"
|
|
27
|
+
},
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public",
|
|
30
|
+
"registry": "https://registry.npmjs.org/"
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/** Stable error raised when a host composes a tool without a required port. */
|
|
2
|
+
export const TOOL_CAPABILITY_UNAVAILABLE = "tool_capability_unavailable";
|
|
3
|
+
|
|
4
|
+
export class ToolCapabilityUnavailableError extends Error {
|
|
5
|
+
readonly code = TOOL_CAPABILITY_UNAVAILABLE;
|
|
6
|
+
readonly toolName: string;
|
|
7
|
+
readonly capability: string;
|
|
8
|
+
|
|
9
|
+
constructor(toolName: string, capability: string) {
|
|
10
|
+
super(`Tool '${toolName}' requires unavailable capability '${capability}'.`);
|
|
11
|
+
this.name = "ToolCapabilityUnavailableError";
|
|
12
|
+
this.toolName = toolName;
|
|
13
|
+
this.capability = capability;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Filesystem and path operations supplied by a host, never by the runtime. */
|
|
18
|
+
export interface FilesystemPort {
|
|
19
|
+
exists(path: string): boolean;
|
|
20
|
+
isFile(path: string): boolean;
|
|
21
|
+
readText(path: string): string;
|
|
22
|
+
writeText(path: string, content: string): void;
|
|
23
|
+
ensureDirectory(path: string): void;
|
|
24
|
+
dirname(path: string): string;
|
|
25
|
+
join(...parts: string[]): string;
|
|
26
|
+
resolve(...parts: string[]): string;
|
|
27
|
+
moduleDirectory(moduleUrl: string): string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Raster persistence is a host edge: render domain code supplies SVG and metadata. */
|
|
31
|
+
export interface RasterOutputPort {
|
|
32
|
+
writeJpeg(input: {
|
|
33
|
+
outputDir: string | undefined;
|
|
34
|
+
outputName: string | undefined;
|
|
35
|
+
graph: string | undefined;
|
|
36
|
+
svg: string;
|
|
37
|
+
width: number;
|
|
38
|
+
layerRows: readonly Record<string, unknown>[];
|
|
39
|
+
}): Promise<{ jpgPath: string }>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Node-only map asset and image-result operations; SVG geometry stays host-neutral. */
|
|
43
|
+
export interface NodeMapPort extends RasterOutputPort {
|
|
44
|
+
mapLayersToBackdrops(rows: readonly Record<string, unknown>[]): {
|
|
45
|
+
backdrops: readonly unknown[];
|
|
46
|
+
resolved: number;
|
|
47
|
+
skipped: number;
|
|
48
|
+
};
|
|
49
|
+
backdropAssetDataHref(backdrop: unknown): string | null;
|
|
50
|
+
attachSpatialGraphImage<T extends { details: object }>(result: T): Promise<T>;
|
|
51
|
+
probeAssetDimensions(input: {
|
|
52
|
+
assetModule: string;
|
|
53
|
+
assetPath: string;
|
|
54
|
+
}): { width: number; height: number } | undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface ToolRunEmitter {
|
|
58
|
+
emit(kind: string, payload: Record<string, unknown>): void;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface ToolTelemetryPort {
|
|
62
|
+
createRunEmitter(input: Record<string, unknown>): ToolRunEmitter;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** One deliberate Node opt-in supplied by a Node/Pi adapter, never defaulted by a tool body. */
|
|
66
|
+
export interface NodeToolCapability {
|
|
67
|
+
filesystem: FilesystemPort;
|
|
68
|
+
map: NodeMapPort;
|
|
69
|
+
telemetry: ToolTelemetryPort;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface NodeToolCapabilities {
|
|
73
|
+
node?: NodeToolCapability;
|
|
74
|
+
}
|
package/src/index.ts
ADDED
package/src/runtime.ts
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import {
|
|
2
|
+
admitsTool,
|
|
3
|
+
getToolContract,
|
|
4
|
+
type LiveToolAuthority,
|
|
5
|
+
type ToolContract,
|
|
6
|
+
type ToolRole,
|
|
7
|
+
} from "@spellkave/tool-contracts";
|
|
8
|
+
import type { Static, TSchema } from "typebox";
|
|
9
|
+
import { Check, Errors } from "typebox/value";
|
|
10
|
+
import { ToolCapabilityUnavailableError } from "./capabilities";
|
|
11
|
+
import { shapeConsequences, type WorldEventCoordinatorPort } from "./world-events";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A host-neutral execution body for one canonical contract. The context and
|
|
15
|
+
* capability ports are supplied only when a host binds the definition; this
|
|
16
|
+
* package never constructs SDK, authoring, filesystem, telemetry, or transport
|
|
17
|
+
* implementations itself.
|
|
18
|
+
*/
|
|
19
|
+
export interface ToolExecutionDefinition<
|
|
20
|
+
TContext,
|
|
21
|
+
P extends TSchema,
|
|
22
|
+
TResult,
|
|
23
|
+
TCapabilities extends object = Record<string, unknown>,
|
|
24
|
+
> {
|
|
25
|
+
contract: string;
|
|
26
|
+
/** A schema structurally identical to the TypeBox schema owned by tool-contracts. */
|
|
27
|
+
schema: P;
|
|
28
|
+
/** Capability keys a host must provide before this definition is exposed. */
|
|
29
|
+
requiredCapabilities?: readonly (keyof TCapabilities & string)[];
|
|
30
|
+
run: (
|
|
31
|
+
context: TContext,
|
|
32
|
+
params: Static<P>,
|
|
33
|
+
toolCallId: string,
|
|
34
|
+
capabilities?: TCapabilities,
|
|
35
|
+
) => Promise<TResult>;
|
|
36
|
+
/** Optional worked-example parameters consumed by host-side doc builders. */
|
|
37
|
+
exampleParams?: Static<P>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Structural authoring operation port; concrete world-author operations stay host-owned. */
|
|
41
|
+
export interface AuthoringOperationPort<TInput, TResult> {
|
|
42
|
+
execute(input: TInput): Promise<TResult>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A canonical descriptor joined with an executable body. */
|
|
46
|
+
export interface ToolDefinition<
|
|
47
|
+
TContext,
|
|
48
|
+
P extends TSchema,
|
|
49
|
+
TResult,
|
|
50
|
+
TCapabilities extends object = Record<string, unknown>,
|
|
51
|
+
> extends Omit<ToolContract, "parameters">,
|
|
52
|
+
ToolExecutionDefinition<TContext, P, TResult, TCapabilities> {
|
|
53
|
+
parameters: P;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The portable tool shape consumed by adapters; it is deliberately not Pi's AgentTool. */
|
|
57
|
+
export interface BoundTool<P extends TSchema, TResult> extends Omit<ToolContract, "parameters"> {
|
|
58
|
+
parameters: P;
|
|
59
|
+
execute: (toolCallId: string, params: Static<P>) => Promise<TResult>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface ToolArgumentIssue {
|
|
63
|
+
path: string;
|
|
64
|
+
message: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Raised before an execution body receives invalid TypeBox arguments. */
|
|
68
|
+
export class ToolArgumentValidationError extends Error {
|
|
69
|
+
readonly toolName: string;
|
|
70
|
+
readonly issues: readonly ToolArgumentIssue[];
|
|
71
|
+
|
|
72
|
+
constructor(toolName: string, issues: readonly ToolArgumentIssue[]) {
|
|
73
|
+
super(`Invalid arguments for '${toolName}'.`);
|
|
74
|
+
this.name = "ToolArgumentValidationError";
|
|
75
|
+
this.toolName = toolName;
|
|
76
|
+
this.issues = issues;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface ToolResultInvocation<TContext, TCapabilities> {
|
|
81
|
+
contract: ToolContract;
|
|
82
|
+
context: TContext;
|
|
83
|
+
capabilities: TCapabilities;
|
|
84
|
+
toolCallId: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Optional host-owned world-event coordination. It is deliberately only a
|
|
89
|
+
* result hook: event acquisition, subscriptions, and transport remain in the
|
|
90
|
+
* SDK and host adapters, while the runtime can coordinate their result shape.
|
|
91
|
+
*/
|
|
92
|
+
export interface WorldEventPort<TContext, TCapabilities, TResult> {
|
|
93
|
+
afterToolResult: (
|
|
94
|
+
result: TResult,
|
|
95
|
+
invocation: ToolResultInvocation<TContext, TCapabilities>,
|
|
96
|
+
) => TResult | Promise<TResult>;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface ToolRuntimePorts<TContext, TCapabilities extends object, TResult> {
|
|
100
|
+
context: TContext;
|
|
101
|
+
capabilities: TCapabilities;
|
|
102
|
+
/**
|
|
103
|
+
* A host-owned, serial event-delta source. When present, the runtime adds
|
|
104
|
+
* the attributable events to the one tool result before any host adapter
|
|
105
|
+
* observes it. SDK subscriptions and buffering stay behind this port.
|
|
106
|
+
*/
|
|
107
|
+
consequences?: WorldEventCoordinatorPort;
|
|
108
|
+
worldEvents?: WorldEventPort<TContext, TCapabilities, TResult>;
|
|
109
|
+
/**
|
|
110
|
+
* Transitional escape hatch for adapters that already validate before they
|
|
111
|
+
* invoke a tool. New runtime compositions use the default true value.
|
|
112
|
+
*/
|
|
113
|
+
validateArguments?: boolean;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export interface ToolRuntimeComposition<TContext, TCapabilities extends object> {
|
|
117
|
+
role?: ToolRole;
|
|
118
|
+
/** Live authority takes precedence over the offline presentation preset. */
|
|
119
|
+
authority?: () => LiveToolAuthority;
|
|
120
|
+
availablePorts?: () => readonly string[];
|
|
121
|
+
context: TContext;
|
|
122
|
+
capabilities: TCapabilities;
|
|
123
|
+
definitions: readonly ToolDefinition<TContext, TSchema, unknown, TCapabilities>[];
|
|
124
|
+
consequences?: WorldEventCoordinatorPort;
|
|
125
|
+
worldEvents?: WorldEventPort<TContext, TCapabilities, unknown>;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function isCapabilityPresent(capabilities: object, name: string): boolean {
|
|
129
|
+
return (
|
|
130
|
+
Object.hasOwn(capabilities, name) &&
|
|
131
|
+
(capabilities as Record<string, unknown>)[name] !== undefined
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function assertCanonicalSchema<P extends TSchema>(contract: ToolContract, schema: P): void {
|
|
136
|
+
if (JSON.stringify(contract.parameters) !== JSON.stringify(schema)) {
|
|
137
|
+
throw new Error(
|
|
138
|
+
`Tool '${contract.name}' must bind the TypeBox schema exported by @spellkave/tool-contracts.`,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Join an execution body to its canonical descriptor without duplicating a
|
|
145
|
+
* schema, name, description, roster, or execution mode in a host package.
|
|
146
|
+
*/
|
|
147
|
+
export function defineTool<
|
|
148
|
+
TContext,
|
|
149
|
+
P extends TSchema,
|
|
150
|
+
TResult,
|
|
151
|
+
TCapabilities extends object = Record<string, unknown>,
|
|
152
|
+
>(
|
|
153
|
+
definition: ToolExecutionDefinition<TContext, P, TResult, TCapabilities>,
|
|
154
|
+
): ToolDefinition<TContext, P, TResult, TCapabilities> {
|
|
155
|
+
const contract = getToolContract(definition.contract);
|
|
156
|
+
assertCanonicalSchema(contract, definition.schema);
|
|
157
|
+
// Contract metadata owns the runtime schema. Some pre-cut companion
|
|
158
|
+
// constants are structurally identical aliases (for example empty-object
|
|
159
|
+
// parameters), so equality is semantic rather than object identity.
|
|
160
|
+
return { ...contract, ...definition, parameters: contract.parameters as P };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function assertValidArguments<P extends TSchema>(
|
|
164
|
+
tool: Pick<BoundTool<P, unknown>, "name" | "parameters">,
|
|
165
|
+
params: unknown,
|
|
166
|
+
): asserts params is Static<P> {
|
|
167
|
+
if (Check(tool.parameters, params)) return;
|
|
168
|
+
const issues = [...Errors(tool.parameters, params)].map((issue) => ({
|
|
169
|
+
path: "path" in issue && typeof issue.path === "string" ? issue.path : "",
|
|
170
|
+
message: issue.message,
|
|
171
|
+
}));
|
|
172
|
+
throw new ToolArgumentValidationError(tool.name, issues);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Bind one definition to explicit context and capability ports. The bound
|
|
177
|
+
* function remains transport-neutral and can be adapted to Pi, MCP, CLI, or a
|
|
178
|
+
* browser host without importing those packages here.
|
|
179
|
+
*/
|
|
180
|
+
export function bindTool<
|
|
181
|
+
TContext,
|
|
182
|
+
P extends TSchema,
|
|
183
|
+
TResult,
|
|
184
|
+
TCapabilities extends object = Record<string, unknown>,
|
|
185
|
+
>(
|
|
186
|
+
definition: ToolDefinition<TContext, P, TResult, TCapabilities>,
|
|
187
|
+
ports: ToolRuntimePorts<TContext, TCapabilities, TResult>,
|
|
188
|
+
): BoundTool<P, TResult> {
|
|
189
|
+
const { context, capabilities, consequences, worldEvents, validateArguments = true } = ports;
|
|
190
|
+
return {
|
|
191
|
+
name: definition.name,
|
|
192
|
+
label: definition.label,
|
|
193
|
+
description: definition.description,
|
|
194
|
+
executionMode: definition.executionMode,
|
|
195
|
+
roles: definition.roles,
|
|
196
|
+
...(definition.promptSnippet === undefined ? {} : { promptSnippet: definition.promptSnippet }),
|
|
197
|
+
...(definition.promptGuidelines === undefined
|
|
198
|
+
? {}
|
|
199
|
+
: { promptGuidelines: definition.promptGuidelines }),
|
|
200
|
+
...(definition.cli === undefined ? {} : { cli: definition.cli }),
|
|
201
|
+
parameters: definition.parameters,
|
|
202
|
+
admission: definition.admission,
|
|
203
|
+
execute: async (toolCallId, params) => {
|
|
204
|
+
const unavailable = (definition.requiredCapabilities ?? []).find(
|
|
205
|
+
(name) => !isCapabilityPresent(capabilities, name),
|
|
206
|
+
);
|
|
207
|
+
if (unavailable !== undefined)
|
|
208
|
+
throw new ToolCapabilityUnavailableError(definition.name, unavailable);
|
|
209
|
+
if (validateArguments) assertValidArguments(definition, params);
|
|
210
|
+
const result = await definition.run(context, params, toolCallId, capabilities);
|
|
211
|
+
const shaped =
|
|
212
|
+
consequences === undefined
|
|
213
|
+
? result
|
|
214
|
+
: (shapeConsequences(result as object, consequences) as TResult);
|
|
215
|
+
if (worldEvents === undefined) return shaped;
|
|
216
|
+
return worldEvents.afterToolResult(shaped, {
|
|
217
|
+
contract: definition,
|
|
218
|
+
context,
|
|
219
|
+
capabilities,
|
|
220
|
+
toolCallId,
|
|
221
|
+
});
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Compose an authorized role roster. A definition is hidden unless its
|
|
228
|
+
* contract authorizes the caller role and every declared capability port is
|
|
229
|
+
* available. Missing ports never cause conditional Node imports.
|
|
230
|
+
*/
|
|
231
|
+
export function createToolRuntime<TContext, TCapabilities extends object>(
|
|
232
|
+
composition: ToolRuntimeComposition<TContext, TCapabilities>,
|
|
233
|
+
): BoundTool<TSchema, unknown>[] {
|
|
234
|
+
return composition.definitions
|
|
235
|
+
.filter((definition) =>
|
|
236
|
+
composition.authority === undefined
|
|
237
|
+
? composition.role !== undefined && definition.roles.includes(composition.role)
|
|
238
|
+
: admitsTool(
|
|
239
|
+
definition.admission,
|
|
240
|
+
composition.authority(),
|
|
241
|
+
composition.availablePorts?.() ?? Object.keys(composition.capabilities),
|
|
242
|
+
),
|
|
243
|
+
)
|
|
244
|
+
.filter((definition) =>
|
|
245
|
+
(definition.requiredCapabilities ?? []).every((name) =>
|
|
246
|
+
isCapabilityPresent(composition.capabilities, name),
|
|
247
|
+
),
|
|
248
|
+
)
|
|
249
|
+
.map((definition) =>
|
|
250
|
+
bindTool(
|
|
251
|
+
{
|
|
252
|
+
...definition,
|
|
253
|
+
run: async (...args) => {
|
|
254
|
+
if (
|
|
255
|
+
composition.authority !== undefined &&
|
|
256
|
+
!admitsTool(
|
|
257
|
+
definition.admission,
|
|
258
|
+
composition.authority(),
|
|
259
|
+
composition.availablePorts?.() ?? Object.keys(composition.capabilities),
|
|
260
|
+
)
|
|
261
|
+
)
|
|
262
|
+
throw new Error(`authority_unavailable: '${definition.name}' is no longer admitted`);
|
|
263
|
+
return definition.run(...args);
|
|
264
|
+
},
|
|
265
|
+
},
|
|
266
|
+
{
|
|
267
|
+
context: composition.context,
|
|
268
|
+
capabilities: composition.capabilities,
|
|
269
|
+
...(composition.consequences === undefined
|
|
270
|
+
? {}
|
|
271
|
+
: { consequences: composition.consequences }),
|
|
272
|
+
...(composition.worldEvents === undefined
|
|
273
|
+
? {}
|
|
274
|
+
: { worldEvents: composition.worldEvents }),
|
|
275
|
+
},
|
|
276
|
+
),
|
|
277
|
+
);
|
|
278
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-safe, host-projected world-delta model (ADR-0083 D-3/D-5 and
|
|
3
|
+
* ADR-0093 D-3).
|
|
4
|
+
*
|
|
5
|
+
* Hosts project only actor-authorized SDK reader results into this module;
|
|
6
|
+
* the runtime never reads raw tables. Fingerprints describe stable semantic
|
|
7
|
+
* identity rather than subscription handles or row revisions, so a
|
|
8
|
+
* content-identical rematerialization remains quiet. Every sample advances
|
|
9
|
+
* the cursor, including a plain read or failed action: only a change that the
|
|
10
|
+
* carrying receipt attributes to the caller is returned as `world_deltas`.
|
|
11
|
+
* Unattributable changes belong to the typed WorldEvent channel instead and
|
|
12
|
+
* must not leak into a later tool receipt.
|
|
13
|
+
*/
|
|
14
|
+
export type DeltaDomain = "scene" | "affordance" | "inventory" | "trace";
|
|
15
|
+
|
|
16
|
+
export interface WorldDeltaItem {
|
|
17
|
+
fingerprint: string;
|
|
18
|
+
name: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface WorldSelfStateProjection {
|
|
22
|
+
state_id: string;
|
|
23
|
+
value: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Projection supplied by an SDK-owning host; no reader implementation leaks here. */
|
|
27
|
+
export interface WorldDeltaProjection {
|
|
28
|
+
scene: readonly WorldDeltaItem[];
|
|
29
|
+
affordance: readonly WorldDeltaItem[];
|
|
30
|
+
inventory: readonly WorldDeltaItem[];
|
|
31
|
+
trace: readonly WorldDeltaItem[];
|
|
32
|
+
self: readonly WorldSelfStateProjection[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** A live session/projection boundary that browser and Node hosts can implement. */
|
|
36
|
+
export interface WorldSessionPort<TSession> {
|
|
37
|
+
currentSession(): TSession | undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A structural projection operation over a host-owned session. */
|
|
41
|
+
export interface WorldProjectionPort<TSession, TProjection> {
|
|
42
|
+
project(session: TSession): TProjection;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Lazily samples one actor-authorized projection from a host subscription cache. */
|
|
46
|
+
export interface WorldDeltaSource {
|
|
47
|
+
sample(): WorldDeltaProjection;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface DomainDeltaNote {
|
|
51
|
+
added: string[];
|
|
52
|
+
removed: string[];
|
|
53
|
+
more: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface SelfStateDelta {
|
|
57
|
+
state_id: string;
|
|
58
|
+
prev: string | null;
|
|
59
|
+
value: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface WorldDeltas {
|
|
63
|
+
scene?: DomainDeltaNote;
|
|
64
|
+
affordance?: DomainDeltaNote;
|
|
65
|
+
inventory?: DomainDeltaNote;
|
|
66
|
+
trace?: DomainDeltaNote;
|
|
67
|
+
self?: SelfStateDelta[];
|
|
68
|
+
self_truncated?: boolean;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface DiffAndAdvanceOptions {
|
|
72
|
+
/** Return this sample's delta only when the carrying receipt caused it. */
|
|
73
|
+
receiptAttributable?: boolean;
|
|
74
|
+
/**
|
|
75
|
+
* A successful own move implies leaving the previous scene; suppress only
|
|
76
|
+
* that scene-removal noise while retaining additions and other domains.
|
|
77
|
+
*/
|
|
78
|
+
suppressSceneRemoved?: boolean;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface DeltaTracker {
|
|
82
|
+
diffAndAdvance(options?: DiffAndAdvanceOptions): WorldDeltas | null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface WorldDeltaContentPort<TContent> {
|
|
86
|
+
contentFor(deltas: WorldDeltas): TContent;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface WorldDeltaResultCoordinator<TContent> extends WorldDeltaContentPort<TContent> {
|
|
90
|
+
tracker: DeltaTracker;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const DOMAINS: readonly DeltaDomain[] = ["scene", "affordance", "inventory", "trace"];
|
|
94
|
+
const MAX_NAMED_PER_DIRECTION = 5;
|
|
95
|
+
const SELF_STATE_CAP = 12;
|
|
96
|
+
|
|
97
|
+
function fingerprintMap(items: readonly WorldDeltaItem[]): Map<string, string> {
|
|
98
|
+
return new Map(items.map((item) => [item.fingerprint, item.name]));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function revision(domain: DeltaDomain, items: Map<string, string>): string {
|
|
102
|
+
return `${domain}:${JSON.stringify([...items].sort(([left], [right]) => left.localeCompare(right)))}`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function diffDomain(
|
|
106
|
+
previous: Map<string, string>,
|
|
107
|
+
next: Map<string, string>,
|
|
108
|
+
dropRemoved: boolean,
|
|
109
|
+
): DomainDeltaNote | null {
|
|
110
|
+
const addedAll = [...next]
|
|
111
|
+
.filter(([fingerprint]) => !previous.has(fingerprint))
|
|
112
|
+
.map(([, name]) => name);
|
|
113
|
+
const removedAll = dropRemoved
|
|
114
|
+
? []
|
|
115
|
+
: [...previous].filter(([fingerprint]) => !next.has(fingerprint)).map(([, name]) => name);
|
|
116
|
+
if (addedAll.length === 0 && removedAll.length === 0) return null;
|
|
117
|
+
const added = addedAll.slice(0, MAX_NAMED_PER_DIRECTION);
|
|
118
|
+
const removed = removedAll.slice(0, MAX_NAMED_PER_DIRECTION);
|
|
119
|
+
return {
|
|
120
|
+
added,
|
|
121
|
+
removed,
|
|
122
|
+
more: addedAll.length - added.length + removedAll.length - removed.length,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Owns semantic fingerprint comparison and cursor advancement, not SDK
|
|
128
|
+
* reads. The first call primes exactly once and is always quiet; recreating a
|
|
129
|
+
* tracker mid-session would discard the prior baseline and is therefore a
|
|
130
|
+
* host lifecycle error (ADR-0083 D-5).
|
|
131
|
+
*/
|
|
132
|
+
export function createWorldDeltaTracker(source: WorldDeltaSource): DeltaTracker {
|
|
133
|
+
const previous = new Map<DeltaDomain, Map<string, string>>();
|
|
134
|
+
const revisions = new Map<DeltaDomain, string>();
|
|
135
|
+
let previousSelf = new Map<string, string>();
|
|
136
|
+
let primed = false;
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
diffAndAdvance(options = {}): WorldDeltas | null {
|
|
140
|
+
const projection = source.sample();
|
|
141
|
+
if (!primed) {
|
|
142
|
+
for (const domain of DOMAINS) {
|
|
143
|
+
const snapshot = fingerprintMap(projection[domain]);
|
|
144
|
+
previous.set(domain, snapshot);
|
|
145
|
+
revisions.set(domain, revision(domain, snapshot));
|
|
146
|
+
}
|
|
147
|
+
previousSelf = new Map(projection.self.map((item) => [item.state_id, item.value]));
|
|
148
|
+
primed = true;
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const out: WorldDeltas = {};
|
|
153
|
+
let changed = false;
|
|
154
|
+
for (const domain of DOMAINS) {
|
|
155
|
+
const next = fingerprintMap(projection[domain]);
|
|
156
|
+
const nextRevision = revision(domain, next);
|
|
157
|
+
const lastRevision = revisions.get(domain);
|
|
158
|
+
const last = previous.get(domain) ?? new Map<string, string>();
|
|
159
|
+
previous.set(domain, next);
|
|
160
|
+
revisions.set(domain, nextRevision);
|
|
161
|
+
if (nextRevision === lastRevision) continue;
|
|
162
|
+
const note = diffDomain(
|
|
163
|
+
last,
|
|
164
|
+
next,
|
|
165
|
+
domain === "scene" && options.suppressSceneRemoved === true,
|
|
166
|
+
);
|
|
167
|
+
if (note !== null) {
|
|
168
|
+
out[domain] = note;
|
|
169
|
+
changed = true;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const nextSelf = new Map(projection.self.map((item) => [item.state_id, item.value]));
|
|
174
|
+
const self = [...nextSelf].flatMap(([state_id, value]) => {
|
|
175
|
+
const prev = previousSelf.get(state_id);
|
|
176
|
+
return prev === value ? [] : [{ state_id, prev: prev ?? null, value }];
|
|
177
|
+
});
|
|
178
|
+
previousSelf = nextSelf;
|
|
179
|
+
if (self.length > 0) {
|
|
180
|
+
changed = true;
|
|
181
|
+
out.self = self.slice(0, SELF_STATE_CAP);
|
|
182
|
+
if (self.length > SELF_STATE_CAP) out.self_truncated = true;
|
|
183
|
+
}
|
|
184
|
+
return options.receiptAttributable === true && changed ? out : null;
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Appends a delta block without reserializing the primary result content. */
|
|
190
|
+
export function appendWorldDeltas<
|
|
191
|
+
TContent,
|
|
192
|
+
TResult extends { content: readonly TContent[]; details: unknown },
|
|
193
|
+
>(result: TResult, deltas: WorldDeltas, port: WorldDeltaContentPort<TContent>): TResult {
|
|
194
|
+
const details =
|
|
195
|
+
typeof result.details === "object" && result.details !== null
|
|
196
|
+
? { ...result.details, world_deltas: deltas }
|
|
197
|
+
: { result: result.details, world_deltas: deltas };
|
|
198
|
+
return { ...result, content: [...result.content, port.contentFor(deltas)], details } as TResult;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Applies a shared tracker only at an explicit host-selected result boundary. */
|
|
202
|
+
export function coordinateWorldDeltas<
|
|
203
|
+
TContent,
|
|
204
|
+
TResult extends { content: readonly TContent[]; details: unknown },
|
|
205
|
+
>(
|
|
206
|
+
result: TResult,
|
|
207
|
+
options: DiffAndAdvanceOptions,
|
|
208
|
+
coordinator: WorldDeltaResultCoordinator<TContent>,
|
|
209
|
+
): TResult {
|
|
210
|
+
const deltas = coordinator.tracker.diffAndAdvance(options);
|
|
211
|
+
return deltas === null ? result : appendWorldDeltas(result, deltas, coordinator);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function truncateSceneNodePathPrefix(currentNodeId: string, toNodeId: string): string {
|
|
215
|
+
const separatorIndex = toNodeId.indexOf("/");
|
|
216
|
+
if (separatorIndex === -1) return toNodeId;
|
|
217
|
+
const toPrefix = toNodeId.slice(0, separatorIndex);
|
|
218
|
+
const currentSeparatorIndex = currentNodeId.indexOf("/");
|
|
219
|
+
const currentPrefix =
|
|
220
|
+
currentSeparatorIndex === -1 ? currentNodeId : currentNodeId.slice(0, currentSeparatorIndex);
|
|
221
|
+
return toPrefix === currentPrefix ? toNodeId.slice(separatorIndex + 1) : toNodeId;
|
|
222
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export {
|
|
2
|
+
type ActPlayerResult,
|
|
3
|
+
type AdvancementAvailableEvent,
|
|
4
|
+
classifyActResult,
|
|
5
|
+
collectConsequences,
|
|
6
|
+
createWorldEventFanout,
|
|
7
|
+
type DealtConditionEvent,
|
|
8
|
+
type DealtHitEvent,
|
|
9
|
+
isCausedByActor,
|
|
10
|
+
type ReactionWindowEvent,
|
|
11
|
+
renderActResultLine,
|
|
12
|
+
renderWorldEventLine,
|
|
13
|
+
type SelfConditionChangedEvent,
|
|
14
|
+
type SelfHitEvent,
|
|
15
|
+
type SelfResourceSpentEvent,
|
|
16
|
+
type SessionLifecycleEvent,
|
|
17
|
+
type SpeechHeardEvent,
|
|
18
|
+
shapeConsequences,
|
|
19
|
+
type TurnTransitionEvent,
|
|
20
|
+
type WorldEvent,
|
|
21
|
+
type WorldEventBuilder,
|
|
22
|
+
type WorldEventCoordinatorPort,
|
|
23
|
+
type WorldEventDeltaSource,
|
|
24
|
+
type WorldEventFanout,
|
|
25
|
+
type WorldEventSource,
|
|
26
|
+
type XpGainedEvent,
|
|
27
|
+
} from "@spellkave/world-events";
|
package/README.md
DELETED