@asterism-app/sdk 1.0.2 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/data-and-lifecycle.md +45 -1
- package/docs/minimal-plugin.md +1 -1
- package/docs/resources-and-tools.md +19 -1
- package/docs/views-and-settings.md +8 -0
- package/examples/author.ts +2 -2
- package/examples/counter/docs/usage.md +1 -1
- package/examples/file-references.ts +39 -0
- package/examples/resource-history.ts +29 -0
- package/package.json +1 -1
- package/src/content-runtime.ts +9 -0
- package/src/contracts.ts +2 -0
- package/src/files.ts +19 -0
- package/src/models.ts +18 -9
- package/src/module-contract.ts +2 -0
- package/src/objects.ts +5 -1
- package/src/records.ts +31 -9
- package/src/renderer-island.ts +6 -2
- package/src/renderer-services.ts +2 -0
- package/src/renderer-tools.ts +3 -1
- package/src/resource-records.ts +28 -0
- package/src/runtime-agent-catalog.ts +1 -1
- package/src/runtime-contracts.ts +13 -4
- package/src/runtime-execution.ts +28 -0
- package/src/runtime-files.ts +7 -0
- package/src/runtime-resources.ts +8 -4
- package/src/runtime-tools.ts +3 -1
- package/src/runtime.ts +5 -2
|
@@ -40,18 +40,62 @@ Use the host's bound read and execution capabilities. Complete network and file
|
|
|
40
40
|
|
|
41
41
|
A historical snapshot fixes what is observed. A later write acts in the current execution context. Holding a snapshot does not redirect later writes into the past.
|
|
42
42
|
|
|
43
|
+
For an operation that other consumers must discover before it finishes, declare an operation record with input and output schemas. Begin it in a synchronous commit to publish the input and obtain its record ID. Complete that ID in a later commit with the output. This fills the result at its original position without moving the cursor. The result can be filled once; input and record identity remain fixed.
|
|
44
|
+
|
|
45
|
+
The record's pending flag distinguishes an unresolved operation from a completed operation whose output is null. Existing snapshots keep their original pending observation; read a new snapshot for current results. Every timeline path containing the operation can read its result, even if another path was selected when it completed.
|
|
46
|
+
|
|
47
|
+
An object writer can complete that object's pending records. A session writer can finish records owned by its plugin after the emitting object leaves the current path. Completion emits a separate observer notification, not a new-record notification. Resource implementations retain responsibility for ending abandoned work rather than waiting for a runtime that no longer exists.
|
|
48
|
+
|
|
43
49
|
Transient events announce change. A consumer needing current state establishes its subscription and reads the current value; later notifications prompt another read.
|
|
44
50
|
|
|
45
51
|
Typed calls describe request and response values with ordinary Zod schemas. The caller supplies the input schema's input; the implementation receives its parsed output, including defaults. The implementation returns JSON accepted by the output schema, and the caller receives that schema's parsed output. These types are inferred from the shared declaration, so a conversion such as string to number does not require separate type annotations.
|
|
46
52
|
|
|
53
|
+
## Read typed history
|
|
54
|
+
|
|
55
|
+
Public record contracts belong to the package that owns their meaning. The SDK exposes host resource creation, renaming, removal, and link changes. A paradigm's public API supplies its conversation records; a plugin's public package supplies its business records. Import the original contract to decode a record rather than interpreting its JSON fields yourself.
|
|
56
|
+
|
|
57
|
+
Use `contract.decode(record)` for a single record and `contract.decodeAll(records)` for a commit batch. Batch decoding preserves the supplied order and omits records belonging to other contracts. A matching record returns either `known` with typed `data`, or `unknown` with the original `record` and an invalid-data reason. An unreadable matching record remains visible for reporting and recovery decisions.
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { ResourceCreated } from "@asterism-app/sdk/contracts";
|
|
61
|
+
|
|
62
|
+
for (const created of ResourceCreated.decodeAll(records)) {
|
|
63
|
+
if (created.status === "unknown") {
|
|
64
|
+
reportUnreadable(created.record);
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
handleCreation(created.data, created.record.sessionId);
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
For stored history, use `snapshot.records.query(ResourceCreated, { scope: "timeline" })`; it returns the same decoded result shape. `first` and `last` select the earliest or latest matching record and preserve `unknown` when that selected record is unreadable. `timeline` selects the snapshot's ancestor path; `session` includes other branches within its captured append bound. These reads retain original record identity and do not rewrite stored data.
|
|
72
|
+
|
|
73
|
+
A creation record separates resource identity, type, title, and encoded resource state. Its `type` is the resource kind. The nested `data` remains JSON because resource kinds have different state contracts; match the resource kind and decode that state with its resource contract when needed. To read a resource present in a snapshot, use `snapshot.resources.get(resourceContract, id)`. Private current-data entries remain owned by their declaring plugin.
|
|
74
|
+
|
|
75
|
+
Creation records include new identities instantiated from templates. Moving through history may make an existing resource appear again without creating a new record. Record observers report committed facts; presence events and attachment lifetimes describe membership in the current resource set. A host-created resource record has a null source, with the associated resource identity in its payload.
|
|
76
|
+
|
|
77
|
+
Public history contracts provide typed observation. Create, rename, remove, and link resources through the session operations; plugin record writers retain their existing ownership checks.
|
|
78
|
+
|
|
47
79
|
## Retain file content
|
|
48
80
|
|
|
49
81
|
Stage immutable bytes through the content service, then store their reference in persistent data or a record that owns them.
|
|
50
82
|
|
|
51
|
-
A
|
|
83
|
+
A `ContentRef` identifies stored immutable content. Copying its identifier does not by itself grant access or retain the bytes. Pass it through the supported operation scope so ownership remains explicit.
|
|
52
84
|
|
|
53
85
|
Retention follows references in the JSON actually saved. Preserve content references in that encoding when their bytes must remain available; synthesizing a reference during decoding does not retain content or grant access.
|
|
54
86
|
|
|
87
|
+
When completing an operation with attachments from an independent temporary scope, supply that scope's content reader. The host validates access and retains those result references in the same transaction as completion. Input references remain retained. Close the temporary scope after completion has committed.
|
|
88
|
+
|
|
89
|
+
## Pass resource file references
|
|
90
|
+
|
|
91
|
+
Use a `FileRef` to pass an address without reading or retaining content. It contains the full source resource identity and a JSON locator interpreted by that resource. Construct it directly and include it in tool results, typed calls, events, or saved state. No registration, content scope, or consumer link is required.
|
|
92
|
+
|
|
93
|
+
The source resource implements `openFile` to interpret its locator and produce an asynchronous byte stream. A consumer uses `plugin.files.open(ref, { signal })` and processes chunks as they arrive. Breaking iteration closes the stream. Forward an operation's cancellation signal so its consumption stops with that operation.
|
|
94
|
+
|
|
95
|
+
Reuse `fileRefSchema` in contracts that return or accept these addresses. Its description supplies the shared meaning. Describe each operation's own use of the reference without coupling its instructions to particular producer or consumer resource types.
|
|
96
|
+
|
|
97
|
+
Discovery returns addresses and descriptive metadata; it need not open files. Each consumption resolves the source anew across sessions, independently of open UI surfaces. The host does not cache bytes or freeze external files. Changed content is read as it exists at consumption, and missing resources, unavailable providers, or failed reads surface as errors. Persisting a file reference preserves its address, not the bytes it once identified. Use immutable content storage when a business operation needs to preserve a particular version.
|
|
98
|
+
|
|
55
99
|
## End asynchronous work
|
|
56
100
|
|
|
57
101
|
Bind shared services to the plugin lifetime and object-owned instances to the resource lifetime. Register cleanup when creating the owned work.
|
package/docs/minimal-plugin.md
CHANGED
|
@@ -18,7 +18,7 @@ The card reads projected data and invokes the public increment action. Each butt
|
|
|
18
18
|
|
|
19
19
|
The example also contributes a Home entry. It prepares a counter, then initializes a session containing it in one transaction. This entry works with the builtin paradigm disabled and requires no conversation input.
|
|
20
20
|
|
|
21
|
-
The model tool reads the same counter value through its resource implementation. Registering the tool does not grant access: an agent needs a link to the counter and
|
|
21
|
+
The model tool reads the same counter value through its resource implementation. Registering the tool does not grant access: an agent needs a link to the counter, and the operation must be available in its execution environment.
|
|
22
22
|
|
|
23
23
|
## Adapt the package
|
|
24
24
|
|
|
@@ -6,7 +6,7 @@ A resource represents an object with identity and lifetime. A tool represents a
|
|
|
6
6
|
|
|
7
7
|
Use a resource for something that belongs in a session and can be inspected or operated on. Define how it is created, what state it owns, and what information it presents.
|
|
8
8
|
|
|
9
|
-
The resource'
|
|
9
|
+
The resource attaches when it becomes present in a session. Removal immediately ends discovery and cancels its managed tasks and model requests. Other owners' requests holding the resource can finish before its attachment lifetime ends and the instance is disposed. A hidden card does not imply that its backend instance should stop.
|
|
10
10
|
|
|
11
11
|
Creation supplies initial state. Actions change the object through typed application or plugin operations. Views present the resulting state.
|
|
12
12
|
|
|
@@ -22,12 +22,30 @@ Use a session snapshot to query the resources directly linked to a receiver. Res
|
|
|
22
22
|
|
|
23
23
|
Use a resource tool when an operation targets a linked object. A shared tool can have implementations for different resource types, each with an appropriate internal target and result.
|
|
24
24
|
|
|
25
|
+
Choose a tool name for the operation's meaning. Reuse an existing tool declaration when its semantics and operation arguments fit another resource; supply that resource's target and result schemas in its implementation. A distinct operation contract needs a distinct name. Domain qualifiers can clarify scope, such as `terminal_input` for terminal interaction, and remain useful when multiple resource types support that operation. Choose qualifiers according to the operation's meaning, independently of whether its declaration is public or where its code lives.
|
|
26
|
+
|
|
27
|
+
For model calls, `resource_id` selects the resource, `args` supplies the operation's parameters, and `target` selects what the operation acts on within that resource. The same tool preserves its meaning and `args` schema across resources. Inspection exposes the tools available on the selected resource and their argument, target, and result schemas.
|
|
28
|
+
|
|
25
29
|
Use a top-level tool for operations on the execution context or shared resource lifecycle, such as creation and renaming. The host supplies caller identity and execution scope.
|
|
26
30
|
|
|
31
|
+
Both resource tools and top-level tools receive `caller`, containing the access owner's resource reference and title. When the executing paradigm supplies an Agent role name, it is available as `caller.agent`. The role identifies the executing configuration independently of the access owner; several roles can execute through one shared resource. Role identity carries no configuration object or additional resource access.
|
|
32
|
+
|
|
27
33
|
Describe the operation's purpose and observable behavior. Parameters should explain business meaning that names and types alone do not express. Results should distinguish known success, failure, cancellation, partial output, and uncertain effects.
|
|
28
34
|
|
|
29
35
|
A tool contribution can capture resource-specific configuration and access at the start of each model request. Return a bound contribution using the same implementation contract; the host uses it for that request's tool batch. This is useful for a resource whose selected network or reachable objects can change while a model is responding. Capture addressing and authorization facts, while reading ordinary mutable content when the operation runs.
|
|
30
36
|
|
|
37
|
+
Declare `requiresInteraction: true` when a tool cannot complete without user interaction. The host excludes it from noninteractive requests and rejects unsupported calls before entering the implementation. Tools supporting both modes can inspect `interactive` in their execution context. A renderer that only displays progress or results does not make a tool interactive.
|
|
38
|
+
|
|
39
|
+
Use `plugin.execution.run` to execute one model request with tools bound to a resource's current links and the real session. Supply that resource as the access owner and select the interaction capability. The execution holds captured relationships through the tool batch; subsequent calls capture current links again. Calls sharing an access owner keep independent message inputs and can run concurrently.
|
|
40
|
+
|
|
41
|
+
Supply the executing role's name through `agent` and any resource type allowlist or denylist through `resources`. The host captures these inputs with the request. Resource policy is enforced by the shared dispatcher: inspection retains resource state and tool schemas with a notice naming a denied role, and calls on restricted types are rejected before the implementation runs. Listing and linked context remain available. Individual resource tools need no role-policy checks.
|
|
42
|
+
|
|
43
|
+
Resource holds do not block history movement. Use an object busy scope for work that depends on the timeline, such as a conversation writing its responses there. Object-bound managed tasks protect history by default; use `affectsHistory: false` for external runtime tasks that should still stop when their owning resource leaves the session.
|
|
44
|
+
|
|
45
|
+
Use `plugin.models.run` when supplying messages and executable tools directly. It needs no workbench resource or timeline. Both forms deliver execution records to the observer you provide. `plugin.execution.withProgress` supplies an optional workbench observer for the events you choose to display.
|
|
46
|
+
|
|
47
|
+
For a temporary conversation, use a content scope to retain generated attachments across requests. Pass it as the input reader and output owner for session-bound execution. Persistent records or a longer-lived scope must retain any surviving results before the temporary scope closes.
|
|
48
|
+
|
|
31
49
|
## Connect other interactions
|
|
32
50
|
|
|
33
51
|
Typed calls connect request and response between services or views. Events announce transient changes. Object channels support sustained data such as an interactive screen.
|
|
@@ -10,6 +10,14 @@ Input previews can be incomplete. Displaying arguments does not establish that e
|
|
|
10
10
|
|
|
11
11
|
Use host presentation facilities for the surrounding card or operation. Keep domain content within the view rather than rebuilding application navigation and containment.
|
|
12
12
|
|
|
13
|
+
## Open expanded content
|
|
14
|
+
|
|
15
|
+
Resource card views can use the renderer island capability to open plugin content beside the workbench. The same entry works from a focused resource. Settings pages and expanded views open additional islands to their own right. Opening another island from the same source level replaces deeper content, subject to close guards.
|
|
16
|
+
|
|
17
|
+
Supply a plugin-local identity, accessible label, opening element, and content renderer. Choose a content surface for an editor or another view that needs more width. The host manages layout and focus. The opened view has an independent plugin region; pass its resource reference and other domain inputs explicitly rather than relying on the source component's React context or mount lifetime.
|
|
18
|
+
|
|
19
|
+
Use the island panel for its title, actions, and close control. Its fill layout lets an editor own scrolling. Mark unsaved content as dirty so closing, replacement, session navigation, and application exit ask before discarding it. A close guard can also retain a view while a save is pending. Closing the island releases its view calls without ending independent backend services.
|
|
20
|
+
|
|
13
21
|
## Style plugin views
|
|
14
22
|
|
|
15
23
|
Import CSS from the renderer entry or its components. Asterism builds the imported styles and loads them before frontend preparation and view registration. CSS references to bundled images and fonts keep their relative paths. Style loading failures appear as frontend plugin failures.
|
package/examples/author.ts
CHANGED
|
@@ -127,8 +127,8 @@ export async function modelWork(plugin: PluginContext, object: ObjectExecutor, s
|
|
|
127
127
|
projectOwnContext: (snapshot: SessionSnapshot, object: ResourceRef) => ModelItem[]) {
|
|
128
128
|
for (let request = 0; request < 8; request++) {
|
|
129
129
|
const snapshot = object.session.snapshot();
|
|
130
|
-
const result = await plugin.
|
|
131
|
-
|
|
130
|
+
const result = await plugin.execution.run({
|
|
131
|
+
access: object.ref, interactive: false, requestParentId: snapshot.position.nodeId, target: { provider: "configured-provider", model: "configured-model" },
|
|
132
132
|
system: { blocks: [{ id: research.name("instruction"), text: "Inspect linked materials and report findings." }] },
|
|
133
133
|
messages: projectOwnContext(snapshot, object.ref), cache: { expectHit: request > 0 }, signal,
|
|
134
134
|
observer: { event(event) {
|
|
@@ -4,6 +4,6 @@ The counter plugin adds a resource that stores an integer, a card for incrementi
|
|
|
4
4
|
|
|
5
5
|
Create a Counter from the workbench creation menu. Its initial value is zero. Use Increment on the card to add the configured step. In plugin settings, change the step or read it back from the backend.
|
|
6
6
|
|
|
7
|
-
Link the counter resource to an agent to make its read operation available
|
|
7
|
+
Link the counter resource to an agent to make its read operation available. The operation reports the current value.
|
|
8
8
|
|
|
9
9
|
Incrementing saves the current value and records the change in history. Browsing an earlier history position does not restore the counter value. Removing the resource removes its current workbench presence while preserving its history.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { createReadStream } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { defineCreation, defineEvent, fileRefSchema, pluginNamespace, type FileRef } from "@asterism-app/sdk/contracts";
|
|
5
|
+
import { defineModule, definePlugin, implementCreation, implementResource, type PluginContext } from "@asterism-app/sdk/runtime";
|
|
6
|
+
|
|
7
|
+
const namespace = pluginNamespace("example.file-source");
|
|
8
|
+
const Folder = namespace.resource("folder", z.object({ path: z.string() }));
|
|
9
|
+
const CreateFolder = defineCreation(Folder, { id: namespace.name("create"), schema: Folder.stateSchema });
|
|
10
|
+
const FolderView = namespace.data("view", Folder.stateSchema);
|
|
11
|
+
export const FileOffered = defineEvent(namespace.name("file-offered"), {
|
|
12
|
+
schema: z.object({ file: fileRefSchema, filename: z.string() }),
|
|
13
|
+
source: "plugin", semantics: { kind: "occurrence" },
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
export default definePlugin({ namespace, modules: [defineModule(() => ({
|
|
17
|
+
events: [FileOffered],
|
|
18
|
+
resources: [implementResource(Folder, FolderView, {
|
|
19
|
+
creation: implementCreation(CreateFolder, { create: data => ({ title: "Files", data }) }),
|
|
20
|
+
project: data => data,
|
|
21
|
+
inspect: async data => data,
|
|
22
|
+
async *openFile(data, locator, { signal }) {
|
|
23
|
+
const { path } = z.object({ path: z.string() }).parse(locator);
|
|
24
|
+
yield* createReadStream(join(data.path, path), { signal });
|
|
25
|
+
},
|
|
26
|
+
})],
|
|
27
|
+
}))] });
|
|
28
|
+
|
|
29
|
+
/** Called with the source plugin's context. Publishing does not check the file or read its bytes. */
|
|
30
|
+
export function offerFile(plugin: PluginContext, file: FileRef, filename: string) {
|
|
31
|
+
plugin.ipc.events.publish(FileOffered, { file, filename });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A consuming plugin subscribes to the shared event contract and streams bytes into its own operation. */
|
|
35
|
+
export function receiveFiles(plugin: PluginContext, consume: (chunks: AsyncIterable<Uint8Array>, filename: string, signal: AbortSignal) => Promise<void>) {
|
|
36
|
+
return plugin.ipc.events.subscribe(FileOffered, { signal: plugin.lifetime.signal }, async ({ data }, { signal }) => {
|
|
37
|
+
await consume(plugin.files.open(data.file, { signal }), data.filename, signal);
|
|
38
|
+
});
|
|
39
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { ResourceCreated, ResourceRemoved, pluginNamespace } from "@asterism-app/sdk/contracts";
|
|
2
|
+
import { defineModule, definePlugin } from "@asterism-app/sdk/runtime";
|
|
3
|
+
|
|
4
|
+
/** Observe public resource facts independently of any resource implementation or Agent paradigm. */
|
|
5
|
+
export default definePlugin({
|
|
6
|
+
namespace: pluginNamespace("example.resource-history"),
|
|
7
|
+
modules: [defineModule(plugin => ({
|
|
8
|
+
observers: [{
|
|
9
|
+
id: "resource-history",
|
|
10
|
+
committed({ records }) {
|
|
11
|
+
for (const created of ResourceCreated.decodeAll(records)) {
|
|
12
|
+
if (created.status === "unknown") {
|
|
13
|
+
plugin.log.error(`Cannot decode creation record ${created.record.id}.`);
|
|
14
|
+
continue;
|
|
15
|
+
}
|
|
16
|
+
const { id, type, title } = created.data;
|
|
17
|
+
plugin.log.info(`Created ${type} resource ${id} in session ${created.record.sessionId}: ${title}`);
|
|
18
|
+
}
|
|
19
|
+
for (const removed of ResourceRemoved.decodeAll(records)) {
|
|
20
|
+
if (removed.status === "unknown") {
|
|
21
|
+
plugin.log.error(`Cannot decode removal record ${removed.record.id}.`);
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
plugin.log.info(`Removed resource ${removed.data.id} from the current path.`);
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
}],
|
|
28
|
+
}))],
|
|
29
|
+
});
|
package/package.json
CHANGED
package/src/content-runtime.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ContentRef, ContentRange } from "./content.ts";
|
|
2
|
+
import type { Json } from "./json.ts";
|
|
2
3
|
|
|
3
4
|
/** Individual reads have a size limit; large content uses bounded byte chunks through open. */
|
|
4
5
|
export interface ContentReader {
|
|
@@ -9,3 +10,11 @@ export interface ContentReader {
|
|
|
9
10
|
export interface ContentScope extends ContentReader {
|
|
10
11
|
stage(source: Uint8Array | AsyncIterable<Uint8Array>): Promise<ContentRef>;
|
|
11
12
|
}
|
|
13
|
+
|
|
14
|
+
export interface RetainedContentScope extends ContentScope {
|
|
15
|
+
retain(value: Json, source: ContentReader): void;
|
|
16
|
+
}
|
|
17
|
+
export interface ContentServices {
|
|
18
|
+
/** Temporary conversation/operation content ownership; nested requests can retain their results here. */
|
|
19
|
+
withScope<T>(work: (content: RetainedContentScope) => Promise<T>): Promise<T>;
|
|
20
|
+
}
|
package/src/contracts.ts
CHANGED
|
@@ -6,6 +6,7 @@ export * from "./module-contract.ts";
|
|
|
6
6
|
export type { CardAppearance } from "./card.ts";
|
|
7
7
|
export * from "./plugin.ts";
|
|
8
8
|
export * from "./records.ts";
|
|
9
|
+
export * from "./resource-records.ts";
|
|
9
10
|
export * from "./events.ts";
|
|
10
11
|
export * from "./calls.ts";
|
|
11
12
|
export * from "./channels.ts";
|
|
@@ -19,6 +20,7 @@ export * from "./commands.ts";
|
|
|
19
20
|
export * from "./i18n.ts";
|
|
20
21
|
export * from "./config.ts";
|
|
21
22
|
export * from "./content.ts";
|
|
23
|
+
export * from "./files.ts";
|
|
22
24
|
export * from "./model-input.ts";
|
|
23
25
|
|
|
24
26
|
export * from "./model-selection.ts";
|
package/src/files.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { jsonSchema } from "./json.ts";
|
|
3
|
+
|
|
4
|
+
/** A self-contained address resolved by its source resource when consumed. References are ordinary, freely constructible JSON. */
|
|
5
|
+
export const fileRefSchema = z.strictObject({
|
|
6
|
+
source: z.strictObject({ sessionId: z.string().min(1), id: z.string().min(1), kind: z.string().min(1) })
|
|
7
|
+
.describe("Full identity of the resource providing the content, including its session."),
|
|
8
|
+
locator: jsonSchema.describe("Location interpreted by the source resource's file provider."),
|
|
9
|
+
}).describe("FileRef: a source resource and a provider-defined locator identifying content fetched when consumed.");
|
|
10
|
+
export type FileRef = z.infer<typeof fileRefSchema>;
|
|
11
|
+
|
|
12
|
+
/** Descriptive metadata travels with a reference; it does not freeze the source content. */
|
|
13
|
+
export const fileReferencePartSchema = z.strictObject({
|
|
14
|
+
kind: z.literal("file-reference"),
|
|
15
|
+
ref: fileRefSchema,
|
|
16
|
+
filename: z.string().min(1).max(255).optional().describe("Name used for delivery."),
|
|
17
|
+
mediaType: z.string().optional().describe("Descriptive MIME type; the reference does not freeze the source content."),
|
|
18
|
+
}).describe("A FileRef with optional delivery metadata.");
|
|
19
|
+
export type FileReferencePart = z.infer<typeof fileReferencePartSchema>;
|
package/src/models.ts
CHANGED
|
@@ -3,7 +3,6 @@ import type { Json } from "./json.ts";
|
|
|
3
3
|
import type { ModelInputPart } from "./model-input.ts";
|
|
4
4
|
import type { ContentReader } from "./content-runtime.ts";
|
|
5
5
|
import type { ToolOutcome, ToolInvocationInfo, ToolResult } from "./tool-result.ts";
|
|
6
|
-
import type { ResourceRef } from "./workspace.ts";
|
|
7
6
|
import type { RequestTiming } from "./model-records.ts";
|
|
8
7
|
import type { Presentation } from "./presentation.ts";
|
|
9
8
|
import type { ErrorDetails } from "./error-details.ts";
|
|
@@ -86,16 +85,26 @@ export interface ModelResponse {
|
|
|
86
85
|
receivedAt: number;
|
|
87
86
|
headers: Readonly<Record<string, string>>;
|
|
88
87
|
}
|
|
89
|
-
export interface
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
88
|
+
export interface ModelToolCall { callId: string; name: string; arguments: Json }
|
|
89
|
+
export interface ModelToolObserver {
|
|
90
|
+
prepared?(call: ModelToolCall, info: ToolInvocationInfo): void;
|
|
91
|
+
started?(call: ModelToolCall, info: ToolInvocationInfo): void;
|
|
92
|
+
published?(call: ModelToolCall, data: Json): void;
|
|
93
|
+
}
|
|
94
|
+
/** Executable tools supplied by the requesting paradigm or a host-bound request environment. */
|
|
95
|
+
export interface ModelTools {
|
|
96
|
+
readonly declarations: readonly { name: string; description: string; parameters: Json }[];
|
|
97
|
+
preview?(name: string, args: Json): ToolInvocationInfo;
|
|
98
|
+
execute(calls: readonly ModelToolCall[], signal: AbortSignal,
|
|
99
|
+
settle: (call: ModelToolCall, outcome: ToolOutcome) => void, observer: ModelToolObserver): Promise<void>;
|
|
100
|
+
}
|
|
101
|
+
export interface ModelRunRequest extends ModelRequestIdentity {
|
|
102
|
+
/** Opaque conversation position returned in output blocks; the caller owns its meaning. */
|
|
93
103
|
requestParentId: string | null;
|
|
94
104
|
target: ModelTarget;
|
|
95
|
-
system: SystemPrompt
|
|
105
|
+
system: SystemPrompt;
|
|
96
106
|
messages: ModelItem[];
|
|
97
|
-
|
|
98
|
-
tools?: { allow?: readonly string[]; exclude?: readonly string[] };
|
|
107
|
+
tools?: ModelTools;
|
|
99
108
|
cache?: { expectHit: boolean };
|
|
100
109
|
/** Synchronously package domain data after final request preparation; delivered with the actual response's completion. */
|
|
101
110
|
completionExtensions?: (context: ModelRequestContext) => readonly Presentation[];
|
|
@@ -129,6 +138,6 @@ export interface ModelServices {
|
|
|
129
138
|
validate(request: Pick<StreamRequest, "target" | "system" | "messages" | "signal" | "userAgent" | "sessionId">, options?: ModelInputOptions): Promise<void>;
|
|
130
139
|
stream(request: StreamRequest, options?: ModelInputOptions): AsyncIterable<ModelEvent>;
|
|
131
140
|
/** One request and its tool batch; neither saves history nor drives the next request. */
|
|
132
|
-
run(request: ModelRunRequest): Promise<ModelRunResult>;
|
|
141
|
+
run(request: ModelRunRequest, options?: ModelInputOptions): Promise<ModelRunResult>;
|
|
133
142
|
list(): readonly { model: string; provider: string; name: string; contextWindow: number | null; capabilities: { reasoning: boolean; tools: boolean; thinkingLevels: readonly ThinkingLevel[] } }[];
|
|
134
143
|
}
|
package/src/module-contract.ts
CHANGED
|
@@ -12,6 +12,8 @@ export interface ToolContract<A extends Json = Json> extends ContractReference {
|
|
|
12
12
|
description: string;
|
|
13
13
|
guidelines: readonly string[];
|
|
14
14
|
argsSchema: z.ZodType<A>;
|
|
15
|
+
/** Execution requires an endpoint that can receive user interaction. Output rendering alone does not require it. */
|
|
16
|
+
requiresInteraction?: boolean;
|
|
15
17
|
}
|
|
16
18
|
/** Tool definitions fix selection descriptions, usage guidance, and args; implementations add only target/result and execution information. */
|
|
17
19
|
export interface ImplementationContract<S extends Json, T extends Json, A extends Json, O extends Json> extends DataContract<O> {
|
package/src/objects.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Json } from "./json.ts";
|
|
2
2
|
import type { DataContract, Presentation } from "./presentation.ts";
|
|
3
|
-
import type { RecordContract } from "./records.ts";
|
|
3
|
+
import type { RecordContract, OperationRecordContract } from "./records.ts";
|
|
4
4
|
import type { ResourceRef, ResourceCreationResult, ResourceSnapshot, SessionSnapshot } from "./workspace.ts";
|
|
5
5
|
import type { ContentReader, ContentScope } from "./content-runtime.ts";
|
|
6
6
|
import type { EventPublisher } from "./events.ts";
|
|
@@ -25,6 +25,10 @@ export interface ResourceActionOptions {
|
|
|
25
25
|
export interface SessionWriter {
|
|
26
26
|
/** Append to the current timeline tip at commit time and advance the cursor; previously obtained read-only snapshots do not determine the append position. */
|
|
27
27
|
append<T extends Json>(contract: RecordContract<T>, data: NoInfer<T>): string;
|
|
28
|
+
/** Publish an operation's immutable input at the current timeline tip, with its result still pending. */
|
|
29
|
+
begin<I extends Json, O extends Json>(contract: OperationRecordContract<I, O>, input: NoInfer<I>): string;
|
|
30
|
+
/** Complete a pending operation on any branch without moving the cursor. Object writers require the same emitting object. */
|
|
31
|
+
complete<I extends Json, O extends Json>(contract: OperationRecordContract<I, O>, id: string, output: NoInfer<O>, options?: { content?: ContentReader }): void;
|
|
28
32
|
set<T extends Json>(contract: DataContract<T>, data: NoInfer<T>): void;
|
|
29
33
|
}
|
|
30
34
|
export type ObjectWriter = SessionWriter;
|
package/src/records.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { z } from "zod";
|
|
2
2
|
import type { Json } from "./json.ts";
|
|
3
3
|
import type { Source } from "./workspace.ts";
|
|
4
4
|
|
|
@@ -17,6 +17,8 @@ export interface SessionRecord {
|
|
|
17
17
|
/** Model-visible text written by the platform, consumed when executors project context; recipient being null means all executors. */
|
|
18
18
|
readonly context: { readonly text: string; readonly recipient: string | null } | null;
|
|
19
19
|
readonly data: Json;
|
|
20
|
+
/** Present for operations published before completion; false after their one-time result is stored. */
|
|
21
|
+
readonly pending?: boolean;
|
|
20
22
|
}
|
|
21
23
|
export type Decoded<D> =
|
|
22
24
|
| { readonly status: "known"; readonly record: SessionRecord; readonly data: D }
|
|
@@ -26,23 +28,43 @@ export interface RecordContract<D extends Json = Json> extends RecordRef {
|
|
|
26
28
|
readonly schema: z.ZodType<D>;
|
|
27
29
|
/** Return null when the record does not belong to this contract; compatibility and transformations are determined by the schema, and failure preserves the raw record. */
|
|
28
30
|
decode(record: SessionRecord): Decoded<D> | null;
|
|
31
|
+
/** Decode a batch in its supplied order, omitting other contracts and retaining unknown matching records. */
|
|
32
|
+
decodeAll(records: readonly SessionRecord[]): Decoded<D>[];
|
|
29
33
|
}
|
|
30
34
|
export function defineRecord<D extends Json>(id: string, definition: {
|
|
31
35
|
schema: z.ZodType<D>;
|
|
32
36
|
}): RecordContract<D> {
|
|
33
37
|
const { schema } = definition;
|
|
38
|
+
const decode = (record: SessionRecord): Decoded<D> | null => {
|
|
39
|
+
if (record.contract.id !== id) return null;
|
|
40
|
+
const data = structuredClone(record.data);
|
|
41
|
+
try {
|
|
42
|
+
const parsed = schema.safeParse(data);
|
|
43
|
+
return parsed.success ? { status: "known", record, data: parsed.data } : { status: "unknown", record, reason: "invalid_data" };
|
|
44
|
+
} catch { return { status: "unknown", record, reason: "invalid_data" }; }
|
|
45
|
+
};
|
|
34
46
|
return {
|
|
35
|
-
id, schema,
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
return parsed.success ? { status: "known", record, data: parsed.data } : { status: "unknown", record, reason: "invalid_data" };
|
|
42
|
-
} catch { return { status: "unknown", record, reason: "invalid_data" }; }
|
|
47
|
+
id, schema, decode,
|
|
48
|
+
decodeAll(records) {
|
|
49
|
+
return records.flatMap(record => {
|
|
50
|
+
const value = decode(record);
|
|
51
|
+
return value ? [value] : [];
|
|
52
|
+
});
|
|
43
53
|
},
|
|
44
54
|
};
|
|
45
55
|
}
|
|
56
|
+
export type OperationData<I extends Json, O extends Json> = { input: I; output: O | null };
|
|
57
|
+
export interface OperationRecordContract<I extends Json = Json, O extends Json = Json> extends RecordContract<OperationData<I, O>> {
|
|
58
|
+
readonly inputSchema: z.ZodType<I>;
|
|
59
|
+
readonly outputSchema: z.ZodType<O>;
|
|
60
|
+
}
|
|
61
|
+
/** Publish input with begin, then fill output once with complete; identity and input remain fixed. */
|
|
62
|
+
export function defineOperationRecord<I extends Json, O extends Json>(id: string, definition: {
|
|
63
|
+
input: z.ZodType<I>; output: z.ZodType<O>;
|
|
64
|
+
}): OperationRecordContract<I, O> {
|
|
65
|
+
return { ...defineRecord(id, { schema: z.strictObject({ input: definition.input, output: definition.output.nullable() }) }),
|
|
66
|
+
inputSchema: definition.input, outputSchema: definition.output };
|
|
67
|
+
}
|
|
46
68
|
/** timeline reads the complete ancestor path to the snapshot tip; session reads all session records within the snapshot's upper bound in save order. */
|
|
47
69
|
export interface RecordQuery { readonly scope: "timeline" | "session" }
|
|
48
70
|
/** An observation handle fixed at one read position; reads records on demand and does not switch to the latest state after await. */
|
package/src/renderer-island.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { createContext, createElement, useContext, useEffect, useRef, type Compo
|
|
|
2
2
|
import type { UiText } from "./i18n.ts";
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* Island: an independent surface column within the host screen
|
|
5
|
+
* Island: an independent surface column within the host screen. Resource cards open beside the workbench, including when focused; other islands open to their own right.
|
|
6
6
|
* The host uniformly manages width, position, motion, and focus; plugins provide only identity, an accessible name, and content.
|
|
7
7
|
*/
|
|
8
8
|
export interface RendererIslandSpec {
|
|
@@ -12,6 +12,8 @@ export interface RendererIslandSpec {
|
|
|
12
12
|
label: UiText;
|
|
13
13
|
/** The element that opened it: used for the expansion animation and receives focus again after closing. */
|
|
14
14
|
origin?: HTMLElement | null;
|
|
15
|
+
/** Content surfaces grow wider than the default form panel. */
|
|
16
|
+
size?: "panel" | "content";
|
|
15
17
|
render: () => ReactNode;
|
|
16
18
|
}
|
|
17
19
|
/** Close guard: returning false (or resolving to false) aborts closing; may asynchronously wait for user confirmation. */
|
|
@@ -40,6 +42,8 @@ export interface RendererIslandPanelProps {
|
|
|
40
42
|
/** Fixed toolbar below the title bar, such as search. */
|
|
41
43
|
toolbar?: ReactNode;
|
|
42
44
|
dirty?: boolean;
|
|
45
|
+
/** Fill the available area without padding; the content owns scrolling. */
|
|
46
|
+
layout?: "padded" | "fill";
|
|
43
47
|
children: ReactNode;
|
|
44
48
|
}
|
|
45
49
|
|
|
@@ -51,7 +55,7 @@ function required<T>(value: T | null, name: string): T {
|
|
|
51
55
|
if (value === null) throw new Error(`Renderer ${name} must be provided by the host.`);
|
|
52
56
|
return value;
|
|
53
57
|
}
|
|
54
|
-
/**
|
|
58
|
+
/** Available within resource cards, plugin settings pages, and islands they open. Opened content has its own region; pass domain inputs explicitly. */
|
|
55
59
|
export function useRendererIsland(): RendererIsland { return required(useContext(Island), "island"); }
|
|
56
60
|
/** Register a close guard for the containing island; null guard permits closing, and the guard always uses the latest callback. */
|
|
57
61
|
export function useRendererCloseGuard(guard: RendererCloseGuard | null) {
|
package/src/renderer-services.ts
CHANGED
|
@@ -17,6 +17,8 @@ export interface RendererCatalogs { get<T extends Json>(contract: DataContract<T
|
|
|
17
17
|
export interface RendererTools {
|
|
18
18
|
resolve(props: ToolRenderProps): ToolView & { props: ToolRenderProps };
|
|
19
19
|
preparation(name: string): string;
|
|
20
|
+
/** Localized name of a tool by its model-facing name and implementation contract; null when no view declares one. */
|
|
21
|
+
label(name: string, implementation: string | null): string | null;
|
|
20
22
|
}
|
|
21
23
|
export interface RendererModels { readonly blocks: readonly ModelLiveBlock[] }
|
|
22
24
|
export interface RendererNavigation { home(): void }
|
package/src/renderer-tools.ts
CHANGED
|
@@ -62,6 +62,8 @@ export interface ToolView {
|
|
|
62
62
|
}
|
|
63
63
|
export interface ToolRenderer {
|
|
64
64
|
contract: ContractReference;
|
|
65
|
+
/** Display name of the tool, readable without rendering a call. */
|
|
66
|
+
label?: UiText;
|
|
65
67
|
resolve(props: ToolRenderProps): ToolView | null;
|
|
66
68
|
}
|
|
67
69
|
|
|
@@ -83,7 +85,7 @@ export function toolRenderer<D extends Json, T extends Json = Json, A extends Js
|
|
|
83
85
|
contract: DataContract<D> & { targetSchema?: z.ZodType<T>; tool?: { argsSchema: z.ZodType<A> } },
|
|
84
86
|
definition: ToolRendererDefinition<D, T, A>,
|
|
85
87
|
): ToolRenderer {
|
|
86
|
-
return { contract: reference(contract), resolve(props) {
|
|
88
|
+
return { contract: reference(contract), label: definition.label, resolve(props) {
|
|
87
89
|
if (props.phase === "input") return definition.input ? render(definition, definition.input, props) : null;
|
|
88
90
|
const data = props.result?.data;
|
|
89
91
|
const parsed = data === null || data === undefined ? null : contract.schema.safeParse(data);
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { defineRecord } from "./records.ts";
|
|
3
|
+
import { jsonSchema } from "./json.ts";
|
|
4
|
+
|
|
5
|
+
/** A new resource identity, including template instances. data is the resource's encoded creation state. */
|
|
6
|
+
export const ResourceCreated = defineRecord("resource_created", {
|
|
7
|
+
schema: z.object({
|
|
8
|
+
id: z.string(),
|
|
9
|
+
type: z.string().min(1),
|
|
10
|
+
title: z.string(),
|
|
11
|
+
data: jsonSchema,
|
|
12
|
+
}),
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
/** A title assignment on the resource's history path. */
|
|
16
|
+
export const ResourceRenamed = defineRecord("resource_renamed", {
|
|
17
|
+
schema: z.object({ id: z.string(), title: z.string() }),
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
/** Removal from the current history path; the resource identity and earlier records remain in history. */
|
|
21
|
+
export const ResourceRemoved = defineRecord("object_removed", {
|
|
22
|
+
schema: z.object({ id: z.string() }),
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
/** id is the resource made available to receiverId; both endpoints are resource identities. */
|
|
26
|
+
const linkSchema = z.object({ id: z.string(), receiverId: z.string() });
|
|
27
|
+
export const ResourceAttached = defineRecord("resource_attached", { schema: linkSchema });
|
|
28
|
+
export const ResourceDetached = defineRecord("resource_detached", { schema: linkSchema });
|
|
@@ -14,7 +14,7 @@ export interface AgentCatalog {
|
|
|
14
14
|
skills(): readonly AgentSkillSource[];
|
|
15
15
|
instructions(): readonly AgentInstruction[];
|
|
16
16
|
refresh(signal: AbortSignal): readonly AgentSkillSource[];
|
|
17
|
-
/** Read current UTF-8 contents from the
|
|
17
|
+
/** Read current UTF-8 contents from the supplied skill package. */
|
|
18
18
|
read(skill: AgentSkill, path: string, signal: AbortSignal): Promise<string>;
|
|
19
19
|
}
|
|
20
20
|
/** Package-relative skill directories; the host supplies the actual contributor identity. */
|
package/src/runtime-contracts.ts
CHANGED
|
@@ -59,6 +59,9 @@ export interface PluginContext {
|
|
|
59
59
|
db(): DatabaseSync;
|
|
60
60
|
readonly tasks: PluginTasks;
|
|
61
61
|
readonly models: ModelServices;
|
|
62
|
+
readonly execution: import("./runtime-execution.ts").ExecutionServices;
|
|
63
|
+
readonly content: import("./content-runtime.ts").ContentServices;
|
|
64
|
+
readonly files: import("./runtime-files.ts").FileServices;
|
|
62
65
|
readonly modelProviders: ModelProviderServices;
|
|
63
66
|
readonly usageProviders: UsageProviderServices;
|
|
64
67
|
readonly usages: UsageServices;
|
|
@@ -82,6 +85,8 @@ export interface SessionCursorChanged {
|
|
|
82
85
|
export interface SessionObserver {
|
|
83
86
|
readonly id: string;
|
|
84
87
|
committed?(event: SessionCommitted): undefined;
|
|
88
|
+
/** Existing operation records received their final outputs; their positions and the cursor are unchanged. */
|
|
89
|
+
completed?(event: SessionCommitted): undefined;
|
|
85
90
|
cursorChanged?(event: SessionCursorChanged): undefined;
|
|
86
91
|
}
|
|
87
92
|
export type Preparation<C extends Json = Json> =
|
|
@@ -126,11 +131,15 @@ export interface ResourceContribution {
|
|
|
126
131
|
project(resource: ResourceSnapshot, object: ObjectReader): Presentation;
|
|
127
132
|
inspect(resource: ResourceSnapshot, object: ObjectReader): Promise<Json>;
|
|
128
133
|
context?(resource: ResourceSnapshot, object: ObjectReader): Promise<ContextFile[]>;
|
|
134
|
+
/** Resolve a file address against this resource at consumption time; consumers need no link or registration of the reference. */
|
|
135
|
+
openFile?(resource: ResourceSnapshot, locator: Json, context: { object: ObjectReader; signal: AbortSignal }): AsyncIterable<Uint8Array>;
|
|
129
136
|
/** Explanation presented to users before ending the current instance; does not block backend removal or wait for external cleanup. */
|
|
130
137
|
disposalWarning?(resource: ResourceSnapshot, object: ObjectReader): UiText | null;
|
|
131
138
|
/**
|
|
132
|
-
* Called synchronously when an object enters the current set through startup, creation, restoration, or rewinding
|
|
133
|
-
*
|
|
139
|
+
* Called synchronously when an object enters the current set through startup, creation, restoration, or rewinding.
|
|
140
|
+
* Removal ends discovery and cancels owned tasks/model requests immediately; attachment lifetime cleanup follows captured request holds.
|
|
141
|
+
* Archival and exit cancel session work before cleanup.
|
|
142
|
+
* Register cleanup here for external instances owned exclusively by the object.
|
|
134
143
|
*/
|
|
135
144
|
attach?(resource: ResourceSnapshot, object: ObjectReader, lifetime: Lifetime): void;
|
|
136
145
|
}
|
|
@@ -141,7 +150,7 @@ export type CallResult<D extends Json = Json> =
|
|
|
141
150
|
| OptionalData<Exclude<ToolCompletion, { kind: "succeeded" | "partial" }>, D>;
|
|
142
151
|
export type PreparedResult = CallResult & ToolInvocationInfo;
|
|
143
152
|
/** Tool caller identity captured at the request boundary; carries neither private resource state nor operation permissions. */
|
|
144
|
-
export type ToolCaller = Readonly<Pick<ResourceSnapshot, "ref" | "title"
|
|
153
|
+
export type ToolCaller = Readonly<Pick<ResourceSnapshot, "ref" | "title"> & { agent?: string }>;
|
|
145
154
|
export interface ToolInvocation extends ToolInvocationInfo {
|
|
146
155
|
effect: "read" | "write";
|
|
147
156
|
execution: "parallel" | "sequential";
|
|
@@ -152,7 +161,7 @@ export interface ToolContribution {
|
|
|
152
161
|
readonly contract: ImplementationContract<Json, Json, Json, Json>;
|
|
153
162
|
/** Bind resource-specific access and configuration at the model request boundary. The returned contribution handles that request's calls. */
|
|
154
163
|
capture?(resource: ResourceSnapshot, object: ObjectReader, caller: ToolCaller): ToolContribution;
|
|
155
|
-
prepare(resource: ResourceSnapshot, object: ObjectExecutor, target: Json, args: Json, caller: ToolCaller): ToolInvocation | PreparedResult;
|
|
164
|
+
prepare(resource: ResourceSnapshot, object: ObjectExecutor, target: Json, args: Json, caller: ToolCaller, interactive: boolean): ToolInvocation | PreparedResult;
|
|
156
165
|
}
|
|
157
166
|
export interface ModuleContribution {
|
|
158
167
|
agentSkills?: readonly AgentSkillDeclaration[];
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { ContentReader, RetainedContentScope } from "./content-runtime.ts";
|
|
2
|
+
import type { ModelRunRequest, ModelRunResult, ModelRunObserver, PromptFile, SystemPrompt } from "./models.ts";
|
|
3
|
+
import type { ResourceRef } from "./workspace.ts";
|
|
4
|
+
|
|
5
|
+
export interface ResourceModelRequest extends Omit<ModelRunRequest, "tools" | "system" | "sessionId"> {
|
|
6
|
+
/** Resource whose current links and tool caller identity supply this request's access. */
|
|
7
|
+
access: ResourceRef;
|
|
8
|
+
/** Paradigm-defined Agent role name, passed to tool implementations as caller identity. */
|
|
9
|
+
agent?: string;
|
|
10
|
+
system: SystemPrompt | ((files: readonly PromptFile[]) => SystemPrompt);
|
|
11
|
+
tools?: { allow?: readonly string[]; exclude?: readonly string[] };
|
|
12
|
+
/** Resource type policy for calls; inspection retains information and adds a restriction notice. */
|
|
13
|
+
resources?: { allow?: readonly string[]; exclude?: readonly string[] };
|
|
14
|
+
/** Whether this execution has a user interaction endpoint. */
|
|
15
|
+
interactive: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface ExecutionContentOptions {
|
|
18
|
+
/** Input content from an independently owned conversation; omission uses the access owner's current history. */
|
|
19
|
+
content?: ContentReader;
|
|
20
|
+
/** Retain tool outputs for subsequent requests in a temporary conversation. */
|
|
21
|
+
output?: RetainedContentScope;
|
|
22
|
+
}
|
|
23
|
+
export interface ExecutionServices {
|
|
24
|
+
/** Capture the owner's environment and hold resources through one request and tool batch. Callers own any timeline busy scope. */
|
|
25
|
+
run(request: ResourceModelRequest, options?: ExecutionContentOptions): Promise<ModelRunResult>;
|
|
26
|
+
/** Optional workbench output sink; the caller decides which execution events to send to it. */
|
|
27
|
+
withProgress<T>(resource: ResourceRef, work: (observer: ModelRunObserver) => Promise<T>): Promise<T>;
|
|
28
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { FileRef } from "./files.ts";
|
|
2
|
+
|
|
3
|
+
/** Each consumption resolves the source anew. Passing or storing a reference performs no I/O and retains no bytes. */
|
|
4
|
+
export interface FileServices {
|
|
5
|
+
/** Pull bytes from the source resource. Breaking iteration closes the stream; cancellation rejects further pulls. Provider errors propagate to the consumer. */
|
|
6
|
+
open(ref: FileRef, options?: { signal?: AbortSignal }): AsyncIterable<Uint8Array>;
|
|
7
|
+
}
|
package/src/runtime-resources.ts
CHANGED
|
@@ -10,6 +10,7 @@ import type { ContextFile, ObjectReader, ObjectExecutor, CreationContribution, A
|
|
|
10
10
|
import { validationMessage, jsonArgumentHint } from "./tool-validation.ts";
|
|
11
11
|
import type { ToolCaller } from "./runtime-contracts.ts";
|
|
12
12
|
import { encodeJson } from "./data-encoding.ts";
|
|
13
|
+
import type { ResourceSnapshot } from "./workspace.ts";
|
|
13
14
|
|
|
14
15
|
function parse<T>(schema: z.ZodType<T>, input: unknown, subject: string): T {
|
|
15
16
|
const result = schema.safeParse(input);
|
|
@@ -46,18 +47,21 @@ export function implementResource<S extends Json, V extends Json>(
|
|
|
46
47
|
project(data: NoInfer<S>, object: ObjectReader): NoInfer<V>;
|
|
47
48
|
inspect(data: NoInfer<S>, object: ObjectReader): Promise<Json>;
|
|
48
49
|
context?(data: NoInfer<S>, object: ObjectReader): Promise<ContextFile[]>;
|
|
50
|
+
openFile?(data: NoInfer<S>, locator: Json, context: { object: ObjectReader; signal: AbortSignal }): AsyncIterable<Uint8Array>;
|
|
49
51
|
disposalWarning?(data: NoInfer<S>, object: ObjectReader): import("./i18n.ts").UiText | null;
|
|
50
52
|
/** Called when an object enters the current set; external instances owned exclusively by the object register cleanup with lifetime. */
|
|
51
53
|
attach?(data: NoInfer<S>, object: ObjectReader, lifetime: Lifetime): void;
|
|
52
54
|
},
|
|
53
55
|
): ResourceContribution {
|
|
54
|
-
const attach = definition
|
|
56
|
+
const { attach, openFile } = definition;
|
|
55
57
|
return {
|
|
56
58
|
resource, card: definition.card, records: [...definition.records ?? []], links: definition.links, template: definition.template,
|
|
57
59
|
creation: definition.creation, actions: definition.actions,
|
|
58
60
|
project: (snapshot, object) => present(view, definition.project(parse(resource.stateSchema, snapshot.data, "resource"), object)),
|
|
59
61
|
inspect: async (snapshot, object) => jsonSchema.parse(await definition.inspect(parse(resource.stateSchema, snapshot.data, "resource"), object)),
|
|
60
62
|
context: async (snapshot, object) => definition.context?.(parse(resource.stateSchema, snapshot.data, "resource"), object) ?? [],
|
|
63
|
+
...(openFile ? { openFile: (snapshot: ResourceSnapshot, locator: Json, context: { object: ObjectReader; signal: AbortSignal }) =>
|
|
64
|
+
openFile(parse(resource.stateSchema, snapshot.data, "resource"), locator, context) } : {}),
|
|
61
65
|
disposalWarning: (snapshot, object) => definition.disposalWarning?.(parse(resource.stateSchema, snapshot.data, "resource"), object) ?? null,
|
|
62
66
|
...(attach ? { attach: (snapshot: Parameters<NonNullable<ResourceContribution["attach"]>>[0], object: ObjectReader, lifetime: Lifetime) =>
|
|
63
67
|
attach(parse(resource.stateSchema, snapshot.data, "resource"), object, lifetime) } : {}),
|
|
@@ -66,7 +70,7 @@ export function implementResource<S extends Json, V extends Json>(
|
|
|
66
70
|
export function implementTool<S extends Json, T extends Json, A extends Json, D extends Json>(
|
|
67
71
|
contract: ImplementationContract<S, T, A, D>, definition: {
|
|
68
72
|
call(data: S, target: T, args: A, context: {
|
|
69
|
-
object: ObjectExecutor; caller: ToolCaller; signal: AbortSignal; publish(data: NoInfer<D>): void;
|
|
73
|
+
object: ObjectExecutor; caller: ToolCaller; signal: AbortSignal; interactive: boolean; publish(data: NoInfer<D>): void;
|
|
70
74
|
}): Promise<CallResult<NoInfer<D>>>;
|
|
71
75
|
toModel?(data: D): ToolModelOutput;
|
|
72
76
|
},
|
|
@@ -74,7 +78,7 @@ export function implementTool<S extends Json, T extends Json, A extends Json, D
|
|
|
74
78
|
const identity = reference(contract);
|
|
75
79
|
return {
|
|
76
80
|
contract: contract as unknown as ToolContribution["contract"],
|
|
77
|
-
prepare(resource, object, target, args, caller) {
|
|
81
|
+
prepare(resource, object, target, args, caller, interactive) {
|
|
78
82
|
const state = contract.resource.stateSchema.safeParse(resource.data);
|
|
79
83
|
if (!state.success) return { kind: "failed", implementation: identity,
|
|
80
84
|
error: { code: "invalid_resource", message: "The resource state does not match its backend contract." } };
|
|
@@ -103,7 +107,7 @@ export function implementTool<S extends Json, T extends Json, A extends Json, D
|
|
|
103
107
|
return encoded;
|
|
104
108
|
};
|
|
105
109
|
try {
|
|
106
|
-
const result = await definition.call(state.data, parsedTarget.data, parsedArgs.data, { object, caller, signal,
|
|
110
|
+
const result = await definition.call(state.data, parsedTarget.data, parsedArgs.data, { object, caller, signal, interactive,
|
|
107
111
|
publish(data) { if (active) publish?.(snapshot(data)); } });
|
|
108
112
|
if (result.kind === "succeeded" || result.kind === "partial") {
|
|
109
113
|
if (result.data === undefined) throw new PluginApiError("invalid_argument", "The tool did not provide final data.");
|
package/src/runtime-tools.ts
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
import { defineTool, type ToolContract } from "./module-contract.ts";
|
|
2
2
|
import type { Json } from "./json.ts";
|
|
3
3
|
import type { ObjectReader, ToolSession } from "./objects.ts";
|
|
4
|
-
import type { CallResult } from "./runtime-contracts.ts";
|
|
4
|
+
import type { CallResult, ToolCaller } from "./runtime-contracts.ts";
|
|
5
5
|
import type { ToolModelOutput } from "./tool-result.ts";
|
|
6
6
|
import type { z } from "zod";
|
|
7
7
|
|
|
8
8
|
export interface TopLevelToolContext<D extends Json = Json> {
|
|
9
9
|
readonly object: ObjectReader;
|
|
10
|
+
readonly caller: ToolCaller;
|
|
10
11
|
readonly session: ToolSession;
|
|
11
12
|
readonly callId: string;
|
|
12
13
|
readonly signal: AbortSignal;
|
|
14
|
+
readonly interactive: boolean;
|
|
13
15
|
publish(data: D): void;
|
|
14
16
|
}
|
|
15
17
|
/** Top-level tools declare their definition and implementation together, independently of resource support relationships. */
|
package/src/runtime.ts
CHANGED
|
@@ -13,7 +13,9 @@ export * from "./runtime-web.ts";
|
|
|
13
13
|
export * from "./runtime-agent-catalog.ts";
|
|
14
14
|
export * from "./runtime-sessions.ts";
|
|
15
15
|
export type * from "./content-runtime.ts";
|
|
16
|
+
export type * from "./runtime-files.ts";
|
|
16
17
|
export type * from "./models.ts";
|
|
18
|
+
export type * from "./runtime-execution.ts";
|
|
17
19
|
export { validationMessage, jsonArgumentHint } from "./tool-validation.ts";
|
|
18
20
|
|
|
19
21
|
/** Stable plugin API error: code supports plugin branching, and message is used for logs. */
|
|
@@ -39,9 +41,10 @@ export interface PluginSecrets {
|
|
|
39
41
|
set(key: string, value: string): Promise<void>;
|
|
40
42
|
delete(key: string): Promise<void>;
|
|
41
43
|
}
|
|
42
|
-
/** Host-managed asynchronous tasks
|
|
44
|
+
/** Host-managed asynchronous tasks: object removal and shutdown cancel owned work and await completion; tasks are not resumed after restart. */
|
|
43
45
|
export interface PluginTasks {
|
|
44
|
-
|
|
46
|
+
/** Object-bound tasks protect the timeline by default; external runtime work can opt out while retaining lifetime ownership. */
|
|
47
|
+
start(key: string, run: (signal: AbortSignal) => Promise<void>, options?: { timeoutMs?: number; object?: ResourceRef; affectsHistory?: boolean }): boolean;
|
|
45
48
|
cancel(key: string): void;
|
|
46
49
|
has(key: string): boolean;
|
|
47
50
|
}
|