@asterism-app/sdk 1.0.2 → 1.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.
@@ -40,6 +40,12 @@ 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.
@@ -52,6 +58,8 @@ A reference identifies content. Copying its identifier does not by itself grant
52
58
 
53
59
  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
60
 
61
+ 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.
62
+
55
63
  ## End asynchronous work
56
64
 
57
65
  Bind shared services to the plugin lifetime and object-owned instances to the resource lifetime. Register cleanup when creating the owned work.
@@ -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 a tool policy that allows the operation.
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's lifetime follows its presence in the session. A hidden card does not imply that its backend instance should stop.
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,26 @@ 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
 
27
31
  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
32
 
29
33
  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
34
 
35
+ 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.
36
+
37
+ 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.
38
+
39
+ 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.
40
+
41
+ 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.
42
+
43
+ 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.
44
+
31
45
  ## Connect other interactions
32
46
 
33
47
  Typed calls connect request and response between services or views. Events announce transient changes. Object channels support sustained data such as an interactive screen.
@@ -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.models.run({
131
- object: object.ref, requestParentId: snapshot.position.nodeId, target: { provider: "configured-provider", model: "configured-model" },
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 under that agent's tool policy. The operation reports the current value.
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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asterism-app/sdk",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "description": "Public contracts and host capabilities for Asterism plugins",
5
5
  "license": "MIT",
6
6
  "author": "Chien Zhang",
@@ -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/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 ModelRunRequest {
90
- object: ResourceRef;
91
- /** Session identity comes from object; callers may declare their own client identity. */
92
- userAgent?: string;
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 | ((files: readonly PromptFile[]) => SystemPrompt);
105
+ system: SystemPrompt;
96
106
  messages: ModelItem[];
97
- /** Filters plugin top-level tools and resource tools selected through actual links by name; does not affect fixed host entry points. */
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
  }
@@ -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 type { z } from "zod";
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 }
@@ -43,6 +45,18 @@ export function defineRecord<D extends Json>(id: string, definition: {
43
45
  },
44
46
  };
45
47
  }
48
+ export type OperationData<I extends Json, O extends Json> = { input: I; output: O | null };
49
+ export interface OperationRecordContract<I extends Json = Json, O extends Json = Json> extends RecordContract<OperationData<I, O>> {
50
+ readonly inputSchema: z.ZodType<I>;
51
+ readonly outputSchema: z.ZodType<O>;
52
+ }
53
+ /** Publish input with begin, then fill output once with complete; identity and input remain fixed. */
54
+ export function defineOperationRecord<I extends Json, O extends Json>(id: string, definition: {
55
+ input: z.ZodType<I>; output: z.ZodType<O>;
56
+ }): OperationRecordContract<I, O> {
57
+ return { ...defineRecord(id, { schema: z.strictObject({ input: definition.input, output: definition.output.nullable() }) }),
58
+ inputSchema: definition.input, outputSchema: definition.output };
59
+ }
46
60
  /** 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
61
  export interface RecordQuery { readonly scope: "timeline" | "session" }
48
62
  /** An observation handle fixed at one read position; reads records on demand and does not switch to the latest state after await. */
@@ -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 }
@@ -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);
@@ -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 captured skill package, independently of later catalog refreshes. */
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. */
@@ -59,6 +59,8 @@ 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;
62
64
  readonly modelProviders: ModelProviderServices;
63
65
  readonly usageProviders: UsageProviderServices;
64
66
  readonly usages: UsageServices;
@@ -82,6 +84,8 @@ export interface SessionCursorChanged {
82
84
  export interface SessionObserver {
83
85
  readonly id: string;
84
86
  committed?(event: SessionCommitted): undefined;
87
+ /** Existing operation records received their final outputs; their positions and the cursor are unchanged. */
88
+ completed?(event: SessionCommitted): undefined;
85
89
  cursorChanged?(event: SessionCursorChanged): undefined;
86
90
  }
87
91
  export type Preparation<C extends Json = Json> =
@@ -129,8 +133,10 @@ export interface ResourceContribution {
129
133
  /** Explanation presented to users before ending the current instance; does not block backend removal or wait for external cleanup. */
130
134
  disposalWarning?(resource: ResourceSnapshot, object: ObjectReader): UiText | null;
131
135
  /**
132
- * Called synchronously when an object enters the current set through startup, creation, restoration, or rewinding that makes it reappear; lifetime ends when the object leaves the current set,
133
- * its session is archived, or the application exits. Register cleanup here for external instances owned exclusively by the object.
136
+ * Called synchronously when an object enters the current set through startup, creation, restoration, or rewinding.
137
+ * Removal ends discovery and cancels owned tasks/model requests immediately; attachment lifetime cleanup follows captured request holds.
138
+ * Archival and exit cancel session work before cleanup.
139
+ * Register cleanup here for external instances owned exclusively by the object.
134
140
  */
135
141
  attach?(resource: ResourceSnapshot, object: ObjectReader, lifetime: Lifetime): void;
136
142
  }
@@ -152,7 +158,7 @@ export interface ToolContribution {
152
158
  readonly contract: ImplementationContract<Json, Json, Json, Json>;
153
159
  /** Bind resource-specific access and configuration at the model request boundary. The returned contribution handles that request's calls. */
154
160
  capture?(resource: ResourceSnapshot, object: ObjectReader, caller: ToolCaller): ToolContribution;
155
- prepare(resource: ResourceSnapshot, object: ObjectExecutor, target: Json, args: Json, caller: ToolCaller): ToolInvocation | PreparedResult;
161
+ prepare(resource: ResourceSnapshot, object: ObjectExecutor, target: Json, args: Json, caller: ToolCaller, interactive: boolean): ToolInvocation | PreparedResult;
156
162
  }
157
163
  export interface ModuleContribution {
158
164
  agentSkills?: readonly AgentSkillDeclaration[];
@@ -0,0 +1,24 @@
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
+ system: SystemPrompt | ((files: readonly PromptFile[]) => SystemPrompt);
9
+ tools?: { allow?: readonly string[]; exclude?: readonly string[] };
10
+ /** Whether this execution has a user interaction endpoint. */
11
+ interactive: boolean;
12
+ }
13
+ export interface ExecutionContentOptions {
14
+ /** Input content from an independently owned conversation; omission uses the access owner's current history. */
15
+ content?: ContentReader;
16
+ /** Retain tool outputs for subsequent requests in a temporary conversation. */
17
+ output?: RetainedContentScope;
18
+ }
19
+ export interface ExecutionServices {
20
+ /** Capture the owner's environment and hold resources through one request and tool batch. Callers own any timeline busy scope. */
21
+ run(request: ResourceModelRequest, options?: ExecutionContentOptions): Promise<ModelRunResult>;
22
+ /** Optional workbench output sink; the caller decides which execution events to send to it. */
23
+ withProgress<T>(resource: ResourceRef, work: (observer: ModelRunObserver) => Promise<T>): Promise<T>;
24
+ }
@@ -66,7 +66,7 @@ export function implementResource<S extends Json, V extends Json>(
66
66
  export function implementTool<S extends Json, T extends Json, A extends Json, D extends Json>(
67
67
  contract: ImplementationContract<S, T, A, D>, definition: {
68
68
  call(data: S, target: T, args: A, context: {
69
- object: ObjectExecutor; caller: ToolCaller; signal: AbortSignal; publish(data: NoInfer<D>): void;
69
+ object: ObjectExecutor; caller: ToolCaller; signal: AbortSignal; interactive: boolean; publish(data: NoInfer<D>): void;
70
70
  }): Promise<CallResult<NoInfer<D>>>;
71
71
  toModel?(data: D): ToolModelOutput;
72
72
  },
@@ -74,7 +74,7 @@ export function implementTool<S extends Json, T extends Json, A extends Json, D
74
74
  const identity = reference(contract);
75
75
  return {
76
76
  contract: contract as unknown as ToolContribution["contract"],
77
- prepare(resource, object, target, args, caller) {
77
+ prepare(resource, object, target, args, caller, interactive) {
78
78
  const state = contract.resource.stateSchema.safeParse(resource.data);
79
79
  if (!state.success) return { kind: "failed", implementation: identity,
80
80
  error: { code: "invalid_resource", message: "The resource state does not match its backend contract." } };
@@ -103,7 +103,7 @@ export function implementTool<S extends Json, T extends Json, A extends Json, D
103
103
  return encoded;
104
104
  };
105
105
  try {
106
- const result = await definition.call(state.data, parsedTarget.data, parsedArgs.data, { object, caller, signal,
106
+ const result = await definition.call(state.data, parsedTarget.data, parsedArgs.data, { object, caller, signal, interactive,
107
107
  publish(data) { if (active) publish?.(snapshot(data)); } });
108
108
  if (result.kind === "succeeded" || result.kind === "partial") {
109
109
  if (result.data === undefined) throw new PluginApiError("invalid_argument", "The tool did not provide final data.");
@@ -10,6 +10,7 @@ export interface TopLevelToolContext<D extends Json = Json> {
10
10
  readonly session: ToolSession;
11
11
  readonly callId: string;
12
12
  readonly signal: AbortSignal;
13
+ readonly interactive: boolean;
13
14
  publish(data: D): void;
14
15
  }
15
16
  /** Top-level tools declare their definition and implementation together, independently of resource support relationships. */
package/src/runtime.ts CHANGED
@@ -14,6 +14,7 @@ export * from "./runtime-agent-catalog.ts";
14
14
  export * from "./runtime-sessions.ts";
15
15
  export type * from "./content-runtime.ts";
16
16
  export type * from "./models.ts";
17
+ export type * from "./runtime-execution.ts";
17
18
  export { validationMessage, jsonArgumentHint } from "./tool-validation.ts";
18
19
 
19
20
  /** Stable plugin API error: code supports plugin branching, and message is used for logs. */
@@ -39,9 +40,10 @@ export interface PluginSecrets {
39
40
  set(key: string, value: string): Promise<void>;
40
41
  delete(key: string): Promise<void>;
41
42
  }
42
- /** Host-managed asynchronous tasks within the process: a running key is not started again, and host shutdown cancels tasks; no timeout by default, and tasks are not resumed after restart. */
43
+ /** Host-managed asynchronous tasks: object removal and shutdown cancel owned work and await completion; tasks are not resumed after restart. */
43
44
  export interface PluginTasks {
44
- start(key: string, run: (signal: AbortSignal) => Promise<void>, options?: { timeoutMs?: number; object?: ResourceRef }): boolean;
45
+ /** Object-bound tasks protect the timeline by default; external runtime work can opt out while retaining lifetime ownership. */
46
+ start(key: string, run: (signal: AbortSignal) => Promise<void>, options?: { timeoutMs?: number; object?: ResourceRef; affectsHistory?: boolean }): boolean;
45
47
  cancel(key: string): void;
46
48
  has(key: string): boolean;
47
49
  }