@asterism-app/sdk 1.3.0 → 1.4.1
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/messaging.md +3 -1
- package/docs/resources-and-tools.md +5 -1
- package/docs/views-and-settings.md +2 -0
- package/examples/author.ts +10 -3
- package/package.json +1 -1
- package/src/files.ts +1 -0
- package/src/messaging.ts +18 -3
- package/src/model-input.ts +4 -1
- package/src/model-records.ts +19 -9
- package/src/models.ts +17 -5
- package/src/objects.ts +5 -0
- package/src/renderer-services.ts +5 -0
- package/src/renderer-tools.ts +2 -0
- package/src/renderer.ts +8 -0
- package/src/runtime-messaging.ts +7 -4
- package/src/runtime-sessions.ts +2 -0
- package/src/runtime-web.ts +2 -1
- package/src/web.ts +2 -2
package/docs/messaging.md
CHANGED
|
@@ -4,7 +4,9 @@ Messaging connects plugins to external conversation services through configured
|
|
|
4
4
|
|
|
5
5
|
Settings use the shared provider setting kinds: text, choice, and secret. Secret values are supplied to the backend factory and remain absent from configuration snapshots. Required values are always present in the resolved settings, choices hold a declared option, and unset optional values are absent. A provider type may have several independently configured connections. The plugin owns any platform-specific state or persistent data used by those connections; declare `forget` to release a removed connection's data, which the host calls after that connection's receiver has ended.
|
|
6
6
|
|
|
7
|
-
An instance supplies its external identity, an ongoing receive operation, conversation listing, message reading, and sending. Receive accepts a cancellation signal and
|
|
7
|
+
An instance supplies its external identity, an ongoing receive operation, conversation listing, message reading, and sending. Receive accepts a cancellation signal and connection-state callbacks, and publishes typed conversation-discovered and message-received events. Call `ready` once the platform has accepted the receiver; the connection then reports connected and its retry backoff resets. A transport that restores its own protocol session calls `reconnecting(error)` during the interruption and `ready()` after recovery, preserving its active receiver. Queries and sends have their own signals. A send carries ordered text and file-reference parts plus an optional reply target. Platforms with a caption field combine the text and deliver the files in order. Resolve each reference with `plugin.files` before contacting the platform, so an unreadable source fails as invalid input without sending anything.
|
|
8
|
+
|
|
9
|
+
Received messages also have ordered text and file parts. File parts identify a platform attachment and describe its MIME type, filename, and known size. An instance's optional `openFile` operation streams the bytes selected by conversation, message, and file IDs. Verify that the selected file belongs to that address, refresh temporary platform URLs as needed, and preserve cancellation and download errors. Resource consumers create FileRefs with their own source identity; provider messages do not depend on a particular card or session.
|
|
8
10
|
|
|
9
11
|
The host retries failed creation and receive calls. Throw `MessagingError` with `request_failed` for transient conditions such as network failures, rate limits, and server errors, and set `retryAfterMs` when the platform reports a delay. Errors other than `MessagingError` are also treated as transient. Use `unavailable` for conditions that retrying cannot fix, such as rejected credentials or a conflicting receiver; the connection then stays failed until the user changes its configuration or reconnects. Reject unsupported operations explicitly with `unsupported`.
|
|
10
12
|
|
|
@@ -16,6 +16,8 @@ Resource titles belong to session history. Use the session's rename operation wi
|
|
|
16
16
|
|
|
17
17
|
Declare `links: { receive: true }` in the backend resource implementation when the object can receive directed links. The host supplies this capability to the workbench's connection controls and authorization panel. Renderer resource descriptions supply labels, icons, and card geometry; link reception needs no frontend declaration.
|
|
18
18
|
|
|
19
|
+
Within a tool, `session.link(receiverId)` exposes the bound caller to a recipient in the request's captured resource scope, and `session.unlink(receiverId)` withdraws that exposure. The host supplies the caller identity. These operations preserve the recipient's link to the caller and cannot authorize additional resources for the caller. Subsequent requests capture the updated relationships; active requests retain their captured access.
|
|
20
|
+
|
|
19
21
|
Use a session snapshot to query the resources directly linked to a receiver. Results contain resource references, titles, and public data on that snapshot's timeline path. Reverse links and links through another resource are independent. For external event handling, such as forwarding network messages to linked agents, read a fresh snapshot for each event. Session observers can also query their supplied snapshot after commits or cursor changes. The query exposes relationships without granting access to private state or expanding a model request's operation scope.
|
|
20
22
|
|
|
21
23
|
## Add a model operation
|
|
@@ -24,7 +26,7 @@ Use a resource tool when an operation targets a linked object. A shared tool can
|
|
|
24
26
|
|
|
25
27
|
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
28
|
|
|
27
|
-
For model calls, `resource_id` selects the resource, `args` supplies the operation's parameters, and `target` selects
|
|
29
|
+
For model calls, `resource_id` selects the resource, `args` supplies the operation's shared parameters, and `target` selects content, scope, or a resource-specific view. A reading target can select a file, a line range, and whether its text includes edit anchors. Each implementation declares the selections it supports. 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
30
|
|
|
29
31
|
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.
|
|
30
32
|
|
|
@@ -44,6 +46,8 @@ Resource holds do not block history movement. Use an object busy scope for work
|
|
|
44
46
|
|
|
45
47
|
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
48
|
|
|
49
|
+
Tool input events arrive in model order before the batch executes. A consumer can begin an operation record for each input, then fill that record when its tool completion event arrives. Progress remains transient. Response termination metadata describes model generation independently of tool outcomes, including available diagnostics after a failed stream. The caller owns retry policy and can use the returned failure's retryability without interpreting provider error strings.
|
|
50
|
+
|
|
47
51
|
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
52
|
|
|
49
53
|
## Connect other interactions
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
Views present state and accept input. Backend services own the work, results, and resource lifetime.
|
|
4
4
|
|
|
5
|
+
Application file services let views open resource FileRefs as byte streams and save a stream through the native Save As dialog. Pass a suggested filename and a lazy stream from the object's content reader or a file reference. Cancelling the dialog returns without reading the stream; ending the stream early abandons the transfer. Transfer failures preserve the old destination and surface as errors; views own their pending indicator and feedback. Previews and exports of captured content read the same immutable bytes.
|
|
6
|
+
|
|
5
7
|
## Present objects and operations
|
|
6
8
|
|
|
7
9
|
A resource card shows the object's content. A tool view shows one operation, including generated input, execution progress, and the final outcome.
|
package/examples/author.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { sample, Counter, Count, CounterView, CountChanged, CreateCounter, ChangeCount, CounterUpdates, counterCard } from "./counter-contract.ts";
|
|
2
2
|
/** Independent examples of session records, resource behavior, and model execution. */
|
|
3
3
|
import { z } from "zod";
|
|
4
|
-
import { pluginNamespace, defineAction, resourceCall, defineRecord, defineTool, defineImplementation,
|
|
4
|
+
import { pluginNamespace, defineAction, resourceCall, defineRecord, defineOperationRecord, defineTool, defineImplementation,
|
|
5
|
+
modelRunRecordSchema, modelBlockSchema, toolOutcomeSchema, type ModelItem } from "@asterism-app/sdk/contracts";
|
|
5
6
|
import {
|
|
6
7
|
defineModule, definePlugin, implementCreation, implementAction, implementPreparer, implementResource, implementTool, implementChannel,
|
|
7
8
|
type PluginContext, type ObjectReader, type ObjectExecutor, type SessionObserver, type SessionSnapshot, type ResourceRef,
|
|
@@ -121,19 +122,25 @@ export const counterPlugin = definePlugin({
|
|
|
121
122
|
/** Scenario three: the plugin's own Agent drives the loop, with context projected from the timeline each time. */
|
|
122
123
|
const research = pluginNamespace("example.research");
|
|
123
124
|
const Execution = defineRecord(research.name("execution"), { schema: modelRunRecordSchema });
|
|
124
|
-
|
|
125
|
+
const ToolExecution = defineOperationRecord(research.name("tool-execution"), { input: modelBlockSchema, output: toolOutcomeSchema });
|
|
126
|
+
export const modelRecordsModule = defineModule(() => ({ records: [Execution, ToolExecution] }));
|
|
125
127
|
/** The domain plugin constructs the projection from its own input/execution events; it is not stored in Agent or run. */
|
|
126
128
|
export async function modelWork(plugin: PluginContext, object: ObjectExecutor, signal: AbortSignal,
|
|
127
129
|
projectOwnContext: (snapshot: SessionSnapshot, object: ResourceRef) => ModelItem[]) {
|
|
128
130
|
for (let request = 0; request < 8; request++) {
|
|
129
131
|
const snapshot = object.session.snapshot();
|
|
132
|
+
const calls = new Map<string, string>();
|
|
130
133
|
const result = await plugin.execution.run({
|
|
131
134
|
access: object.ref, interactive: false, requestParentId: snapshot.position.nodeId, target: { provider: "configured-provider", model: "configured-model" },
|
|
132
135
|
system: { blocks: [{ id: research.name("instruction"), text: "Inspect linked materials and report findings." }] },
|
|
133
136
|
messages: projectOwnContext(snapshot, object.ref), cache: { expectHit: request > 0 }, signal,
|
|
134
137
|
observer: { event(event) {
|
|
135
138
|
if (event.type === "progress") return;
|
|
136
|
-
object.commit(writer => {
|
|
139
|
+
object.commit(writer => {
|
|
140
|
+
if (event.type === "tool.begin") calls.set(event.block.callId, writer.begin(ToolExecution, event.block));
|
|
141
|
+
else if (event.type === "tool.complete") writer.complete(ToolExecution, calls.get(event.block.callId)!, event.block.outcome!);
|
|
142
|
+
else writer.append(Execution, modelRunRecordSchema.parse(event));
|
|
143
|
+
});
|
|
137
144
|
} },
|
|
138
145
|
});
|
|
139
146
|
if (result.reason !== "completed" || result.tools.length === 0) return result;
|
package/package.json
CHANGED
package/src/files.ts
CHANGED
|
@@ -15,5 +15,6 @@ export const fileReferencePartSchema = z.strictObject({
|
|
|
15
15
|
ref: fileRefSchema,
|
|
16
16
|
filename: z.string().min(1).max(255).optional().describe("Name used for delivery."),
|
|
17
17
|
mediaType: z.string().optional().describe("Descriptive MIME type; the reference does not freeze the source content."),
|
|
18
|
+
size: z.number().int().nonnegative().optional().describe("Byte size observed when the reference was described."),
|
|
18
19
|
}).describe("A FileRef with optional delivery metadata.");
|
|
19
20
|
export type FileReferencePart = z.infer<typeof fileReferencePartSchema>;
|
package/src/messaging.ts
CHANGED
|
@@ -34,10 +34,18 @@ export const conversationSchema = conversationAddressSchema.extend({
|
|
|
34
34
|
*/
|
|
35
35
|
export const messageSenderRoleSchema = z.enum(["self", "participant", "system"]);
|
|
36
36
|
export const messageSenderSchema = z.strictObject({ id, name: z.string(), role: messageSenderRoleSchema });
|
|
37
|
+
export const messagingFilePartSchema = z.strictObject({
|
|
38
|
+
kind: z.literal("file"), id,
|
|
39
|
+
filename: z.string().optional(), mediaType: z.string(),
|
|
40
|
+
size: z.number().int().nonnegative().optional(),
|
|
41
|
+
});
|
|
42
|
+
export const messagingTextPartSchema = z.strictObject({ kind: z.literal("text"), text: z.string() });
|
|
43
|
+
export const messagingPartSchema = z.discriminatedUnion("kind", [messagingTextPartSchema, messagingFilePartSchema]);
|
|
37
44
|
export const messageSchema = z.strictObject({
|
|
38
|
-
id, sender: messageSenderSchema,
|
|
45
|
+
id, sender: messageSenderSchema, parts: z.array(messagingPartSchema),
|
|
39
46
|
sentAt: z.string(), replyTo: id.optional(), threadId: id.optional(),
|
|
40
47
|
});
|
|
48
|
+
export const messagingFileQuerySchema = conversationAddressSchema.extend({ messageId: id, fileId: id });
|
|
41
49
|
export const conversationQuerySchema = z.strictObject({ since: id.optional() });
|
|
42
50
|
export const conversationListSchema = z.strictObject({
|
|
43
51
|
conversations: z.array(conversationSchema), cursor: id.optional(), truncated: z.boolean(),
|
|
@@ -50,8 +58,9 @@ export const messageListSchema = z.strictObject({
|
|
|
50
58
|
});
|
|
51
59
|
/** Files are references resolved by the provider when sending; text accompanies them as a caption. */
|
|
52
60
|
export const sendMessageSchema = conversationAddressSchema.extend({
|
|
53
|
-
|
|
54
|
-
|
|
61
|
+
parts: z.array(z.union([messagingTextPartSchema, fileReferencePartSchema])).min(1),
|
|
62
|
+
replyTo: id.optional(),
|
|
63
|
+
}).refine(value => value.parts.some(part => part.kind === "file-reference" || part.text.trim()), "A message requires text or a file.");
|
|
55
64
|
export const messagingEventSchema = z.discriminatedUnion("kind", [
|
|
56
65
|
z.strictObject({ kind: z.literal("conversation.discovered"), conversation: conversationSchema }),
|
|
57
66
|
z.strictObject({ kind: z.literal("message.received"), conversation: conversationSchema, message: messageSchema }),
|
|
@@ -64,6 +73,12 @@ export type ConversationAddress = z.infer<typeof conversationAddressSchema>;
|
|
|
64
73
|
export type MessagingConversation = z.infer<typeof conversationSchema>;
|
|
65
74
|
export type MessageSenderRole = z.infer<typeof messageSenderRoleSchema>;
|
|
66
75
|
export type MessagingMessage = z.infer<typeof messageSchema>;
|
|
76
|
+
export type MessagingFilePart = z.infer<typeof messagingFilePartSchema>;
|
|
77
|
+
export type MessagingPart = z.infer<typeof messagingPartSchema>;
|
|
78
|
+
export type MessagingFileQuery = z.infer<typeof messagingFileQuerySchema>;
|
|
79
|
+
export function messagingText(message: { parts: readonly MessagingPart[] }): string {
|
|
80
|
+
return message.parts.map(part => part.kind === "text" ? part.text : `[File: ${part.filename ?? part.id}]`).join("\n");
|
|
81
|
+
}
|
|
67
82
|
export type ConversationQuery = z.infer<typeof conversationQuerySchema>;
|
|
68
83
|
export type ConversationList = z.infer<typeof conversationListSchema>;
|
|
69
84
|
export type MessageQuery = z.infer<typeof messageQuerySchema>;
|
package/src/model-input.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { contentRefSchema } from "./content.ts";
|
|
3
|
+
import { fileRefSchema } from "./files.ts";
|
|
3
4
|
|
|
4
5
|
/** mediaType is the MIME type truthfully identified by the client and sent with the bytes; the client does not infer model capabilities from it, and acceptance is determined by server feedback. */
|
|
5
6
|
export const mediaTypeSchema = z.string().regex(/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/);
|
|
@@ -8,7 +9,9 @@ export const mediaTypeSchema = z.string().regex(/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$
|
|
|
8
9
|
export const modelInputPartSchema = z.discriminatedUnion("kind", [
|
|
9
10
|
z.strictObject({ kind: z.literal("text"), text: z.string() }),
|
|
10
11
|
z.strictObject({ kind: z.literal("file"), file: contentRefSchema,
|
|
11
|
-
mediaType: mediaTypeSchema, filename: z.string().min(1).max(255).optional()
|
|
12
|
+
mediaType: mediaTypeSchema, filename: z.string().min(1).max(255).optional(),
|
|
13
|
+
size: z.number().int().nonnegative().optional(),
|
|
14
|
+
ref: fileRefSchema.optional().describe("Resource address for saving or forwarding the captured file.") }),
|
|
12
15
|
]);
|
|
13
16
|
export type ModelInputPart = z.infer<typeof modelInputPartSchema>;
|
|
14
17
|
export type ModelFilePart = Extract<ModelInputPart, { kind: "file" }>;
|
package/src/model-records.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** Shared payloads for model execution; consuming plugins declare RecordContract identities, and the SDK does not create a separate history. */
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { jsonSchema, type Json } from "./json.ts";
|
|
4
|
-
import { toolOutcomeSchema } from "./tool-result.ts";
|
|
4
|
+
import { toolOutcomeSchema, toolInvocationSchema } from "./tool-result.ts";
|
|
5
5
|
import { presentationSchema, type DataContract } from "./presentation.ts";
|
|
6
6
|
import type { ModelCompletion } from "./models.ts";
|
|
7
7
|
import { errorDetailsSchema } from "./error-details.ts";
|
|
@@ -27,9 +27,16 @@ export const requestTimingSchema = z.strictObject({
|
|
|
27
27
|
export type RequestTiming = z.infer<typeof requestTimingSchema>;
|
|
28
28
|
|
|
29
29
|
export const modelSourceSchema = z.strictObject({ model: z.string(), adapter: z.string(), scope: z.string() });
|
|
30
|
-
export const
|
|
30
|
+
export const modelTerminationSchema = z.discriminatedUnion("reason", [
|
|
31
|
+
z.strictObject({ reason: z.literal("completed") }),
|
|
32
|
+
z.strictObject({ reason: z.literal("cancelled") }),
|
|
33
|
+
z.strictObject({ reason: z.literal("failed"), origin: z.enum(["model", "software"]), code: z.string(), message: z.string(),
|
|
34
|
+
retryable: z.boolean(), details: errorDetailsSchema.optional() }),
|
|
35
|
+
]);
|
|
36
|
+
/** finishReason is the provider-reported reason; it is null when generation ended before the provider reported one. */
|
|
37
|
+
export const modelCompletionSchema = z.strictObject({ usage: modelUsageSchema.nullable(), finishReason: z.string().nullable(),
|
|
31
38
|
rawFinishReason: z.string().nullable(), providerResponseId: z.string().nullable(), timing: requestTimingSchema.optional(),
|
|
32
|
-
extensions: z.array(presentationSchema).optional() });
|
|
39
|
+
termination: modelTerminationSchema.optional(), extensions: z.array(presentationSchema).optional() });
|
|
33
40
|
/** Decode only domain extensions known to the caller; unknown or undecodable extensions do not affect the public terminal state. */
|
|
34
41
|
export function completionData<T extends Json>(completion: ModelCompletion | null | undefined, contract: DataContract<T>): T | null {
|
|
35
42
|
const extension = completion?.extensions?.find(value => value.contract.id === contract.id);
|
|
@@ -41,16 +48,19 @@ const block = { responseId: id, requestParentId: id.nullable(), ordinal: z.numbe
|
|
|
41
48
|
complete: z.boolean(), continuation: jsonSchema, source: modelSourceSchema, completion: modelCompletionSchema.nullable().optional(),
|
|
42
49
|
/** Block generation start and end times (millisecond timestamps); blocks finalized before generation ends have a null end time, and unrecorded times are omitted. See outcome for tool execution times. */
|
|
43
50
|
startedAt: z.number().nonnegative().optional(), endedAt: z.number().nonnegative().nullable().optional() };
|
|
51
|
+
/** Tool call block shape without the completion invariant, for contracts that store input and outcome separately. */
|
|
52
|
+
export const modelToolCallBlockSchema = z.strictObject({ ...block, kind: z.literal("toolcall"), callId: id, name: id,
|
|
53
|
+
/** Original model text; retained only when parsed arguments are unavailable (the call is incomplete), otherwise arguments is authoritative. */
|
|
54
|
+
argumentsText: z.string().nullable(), arguments: jsonSchema, outcome: toolOutcomeSchema.nullable(), invocation: toolInvocationSchema.optional() });
|
|
44
55
|
export const modelBlockSchema = z.discriminatedUnion("kind", [
|
|
45
56
|
z.strictObject({ ...block, kind: z.literal("thinking"), text: z.string(), summary: z.string() }),
|
|
46
57
|
z.strictObject({ ...block, kind: z.literal("text"), text: z.string() }),
|
|
47
|
-
|
|
48
|
-
/** Original model text; retained only when parsed arguments are unavailable (the call is incomplete), otherwise arguments is authoritative. */
|
|
49
|
-
argumentsText: z.string().nullable(), arguments: jsonSchema, outcome: toolOutcomeSchema.nullable() })
|
|
50
|
-
.refine(data => data.complete === (data.outcome !== null), "Complete tool calls must have an outcome."),
|
|
58
|
+
modelToolCallBlockSchema.refine(data => data.complete === (data.outcome !== null), "Complete tool calls must have an outcome."),
|
|
51
59
|
]);
|
|
52
|
-
/**
|
|
60
|
+
/** Generation termination is embedded in blocks; tool publication and completion preserve a fixed input position. */
|
|
53
61
|
export const modelRunRecordSchema = z.discriminatedUnion("type", [
|
|
54
62
|
z.strictObject({ type: z.literal("block"), block: modelBlockSchema }),
|
|
55
|
-
z.strictObject({ type: z.literal("
|
|
63
|
+
z.strictObject({ type: z.literal("tool.begin"), block: modelBlockSchema }),
|
|
64
|
+
z.strictObject({ type: z.literal("tool.complete"), block: modelBlockSchema }),
|
|
65
|
+
z.strictObject({ type: z.literal("diagnostic"), origin: z.enum(["model", "software"]), code: z.string(), message: z.string(), level: z.enum(["error", "warning"]), details: errorDetailsSchema.optional(), responseId: id.optional() }),
|
|
56
66
|
]);
|
package/src/models.ts
CHANGED
|
@@ -39,13 +39,21 @@ export type ModelEvent =
|
|
|
39
39
|
| { type: "part.end"; partId: string; arguments?: Json; continuation?: Json }
|
|
40
40
|
| { type: "finish"; reason: string; usage: Usage | null; responseId?: string; rawFinishReason?: string; source?: ModelSource; timing?: RequestTiming; response?: ModelResponse | null };
|
|
41
41
|
export type ModelSource = { model: string; adapter: string; scope: string };
|
|
42
|
+
export type ModelTermination =
|
|
43
|
+
| { reason: "completed" }
|
|
44
|
+
| { reason: "cancelled" }
|
|
45
|
+
| { reason: "failed"; origin: "model" | "software"; code: string; message: string; retryable: boolean; details?: ErrorDetails };
|
|
42
46
|
export type ModelCompletion = {
|
|
43
|
-
usage: Usage | null;
|
|
47
|
+
usage: Usage | null;
|
|
48
|
+
/** Provider-reported finish reason; null when generation ended before the provider reported one. */
|
|
49
|
+
finishReason: string | null; rawFinishReason: string | null; providerResponseId: string | null;
|
|
44
50
|
timing?: RequestTiming;
|
|
51
|
+
/** How model generation ended, independently of subsequent tool execution. Omitted in older history. */
|
|
52
|
+
termination?: ModelTermination;
|
|
45
53
|
/** Typed data declared and consumed by the domain; the public layer preserves unknown contracts. */
|
|
46
54
|
extensions?: Presentation[];
|
|
47
55
|
};
|
|
48
|
-
/**
|
|
56
|
+
/** Response blocks, including published tool inputs; consumers own timeline identity and one-time outcome persistence. */
|
|
49
57
|
export type ModelBlock = {
|
|
50
58
|
responseId: string; requestParentId: string | null; ordinal: number; complete: boolean; continuation: Json; source: ModelSource;
|
|
51
59
|
/** Terminal state is delivered once with the actual response block having the highest ordinal; null for all other blocks. */
|
|
@@ -55,7 +63,9 @@ export type ModelBlock = {
|
|
|
55
63
|
} & (
|
|
56
64
|
| { kind: "thinking"; text: string; summary: string }
|
|
57
65
|
| { kind: "text"; text: string }
|
|
58
|
-
| { kind: "toolcall"; callId: string; name: string; argumentsText: string | null; arguments: Json; outcome: ToolOutcome | null
|
|
66
|
+
| { kind: "toolcall"; callId: string; name: string; argumentsText: string | null; arguments: Json; outcome: ToolOutcome | null;
|
|
67
|
+
/** Original input preview identity; available even when execution never produced an outcome. */
|
|
68
|
+
invocation?: ToolInvocationInfo }
|
|
59
69
|
);
|
|
60
70
|
export type ModelLiveBlock = { id: string; responseId: string; ordinal: number } & (
|
|
61
71
|
| { kind: "text"; text: string; endedAt: number | null }
|
|
@@ -66,8 +76,10 @@ export type ModelLiveBlock = { id: string; responseId: string; ordinal: number }
|
|
|
66
76
|
);
|
|
67
77
|
export type ModelRunEvent =
|
|
68
78
|
| { type: "block"; block: ModelBlock }
|
|
79
|
+
| { type: "tool.begin"; block: Extract<ModelBlock, { kind: "toolcall" }> }
|
|
80
|
+
| { type: "tool.complete"; block: Extract<ModelBlock, { kind: "toolcall" }> }
|
|
69
81
|
| { type: "progress"; blocks: readonly ModelLiveBlock[] }
|
|
70
|
-
| { type: "diagnostic"; origin: "model" | "software"; code: string; message: string; level: "error" | "warning"; details?: ErrorDetails };
|
|
82
|
+
| { type: "diagnostic"; origin: "model" | "software"; code: string; message: string; level: "error" | "warning"; details?: ErrorDetails; responseId?: string };
|
|
71
83
|
/** Deliver execution events synchronously; consumers save finalized records, exceptions stop execution, and no further events are delivered after returning. */
|
|
72
84
|
export interface ModelRunObserver { event(event: ModelRunEvent): undefined }
|
|
73
85
|
/** Used only for HTTP request identity; does not enter model messages, history, or resource authorization. */
|
|
@@ -117,7 +129,7 @@ export type ModelRunResult = {
|
|
|
117
129
|
response: ModelResponse | null;
|
|
118
130
|
/** Measured timing for this call; still available for transient feedback when no terminal state was obtained. */
|
|
119
131
|
timing: RequestTiming | null;
|
|
120
|
-
} & ({ reason: "completed" } | { reason: "cancelled" } | { reason: "failed"; code: string; details?: ErrorDetails });
|
|
132
|
+
} & ({ reason: "completed" } | { reason: "cancelled" } | { reason: "failed"; code: string; details?: ErrorDetails; retryable?: boolean });
|
|
121
133
|
/** The final request's input context; an independent copy for domain extension producers to read. */
|
|
122
134
|
export interface ModelRequestContext {
|
|
123
135
|
system: SystemPrompt;
|
package/src/objects.ts
CHANGED
|
@@ -60,6 +60,7 @@ export interface SessionExecutor extends SessionReader {
|
|
|
60
60
|
* An operation facade for the same session from the perspective of the tool caller and this request.
|
|
61
61
|
* The host binds the originating resource, the effective link scope at request start, and the tool execution scope, handling identity and execution validation consistently.
|
|
62
62
|
* Operations originate from the initiating resource: newly created resources link to it, while removal and rename targets resolve within this request's effective link scope.
|
|
63
|
+
* Link operations expose the initiator to a recipient within that same scope; the initiator is always the resource being shared.
|
|
63
64
|
* New operations use this perspective, explicitly defining implicitly bound endpoints, the operable resource scope, and the execution scope.
|
|
64
65
|
*/
|
|
65
66
|
export interface ToolSession extends SessionReader {
|
|
@@ -68,6 +69,10 @@ export interface ToolSession extends SessionReader {
|
|
|
68
69
|
/** Link the bound initiator to the new resource, committed atomically with creation; defaults to false when omitted. */
|
|
69
70
|
exposeSelf?: boolean;
|
|
70
71
|
}): Promise<ResourceCreationResult>;
|
|
72
|
+
/** Expose the bound initiator to a recipient in this request's effective link scope. The recipient must support receiving links. */
|
|
73
|
+
link(receiverId: string): void;
|
|
74
|
+
/** Withdraw the bound initiator's exposure to a recipient in this request's effective link scope; preserve the reverse link. */
|
|
75
|
+
unlink(receiverId: string): void;
|
|
71
76
|
remove(resourceId: string): void;
|
|
72
77
|
rename(resourceId: string, title: string): string;
|
|
73
78
|
}
|
package/src/renderer-services.ts
CHANGED
|
@@ -85,6 +85,11 @@ export interface RendererApplicationServices {
|
|
|
85
85
|
preferences(pluginId: string): import("./renderer-creation.ts").RendererPreferences;
|
|
86
86
|
pickDirectory(initialPath?: string): Promise<string | null>;
|
|
87
87
|
openLocalFile(path: string): Promise<void>;
|
|
88
|
+
readonly files: {
|
|
89
|
+
open(ref: import("./files.ts").FileRef): AsyncIterable<Uint8Array>;
|
|
90
|
+
/** Show the system Save As dialog, then consume the stream. Returns false when the user cancels. */
|
|
91
|
+
save(filename: string, source: AsyncIterable<Uint8Array>): Promise<boolean>;
|
|
92
|
+
};
|
|
88
93
|
}
|
|
89
94
|
const Application = createContext<RendererApplicationServices | null>(null);
|
|
90
95
|
export const RendererApplicationProvider = Application.Provider;
|
package/src/renderer-tools.ts
CHANGED
|
@@ -15,6 +15,8 @@ interface ToolCallProps<T, A> {
|
|
|
15
15
|
export interface ToolInputRenderProps extends ToolCallProps<Json, Json> {
|
|
16
16
|
phase: "input";
|
|
17
17
|
result: null;
|
|
18
|
+
/** Original unfinished input; the host derives a display-only argument preview when resolving the view. */
|
|
19
|
+
argumentsText?: string;
|
|
18
20
|
}
|
|
19
21
|
/** Waiting for scheduling and execution share a view; complete arguments have passed contract validation. */
|
|
20
22
|
export interface ToolExecutionRenderProps<D = Json, T = Json, A = Json> extends ToolCallProps<T, A> {
|
package/src/renderer.ts
CHANGED
|
@@ -119,10 +119,18 @@ export interface PluginSettingsPage {
|
|
|
119
119
|
locations?: readonly string[];
|
|
120
120
|
Body: ComponentType<{ location?: string }>;
|
|
121
121
|
}
|
|
122
|
+
/** Host folder selection for the next session started from the entry. */
|
|
123
|
+
export interface SessionEntryFolder {
|
|
124
|
+
/** Selected folder identity, or null for no folder; pass it as the `folderId` session creation option. */
|
|
125
|
+
readonly id: string | null;
|
|
126
|
+
/** Host-rendered folder control for the entry's own toolbar; selection and folder creation stay with the host. */
|
|
127
|
+
readonly Picker: ComponentType<{ disabled?: boolean }>;
|
|
128
|
+
}
|
|
122
129
|
export interface SessionEntryProps {
|
|
123
130
|
active: boolean;
|
|
124
131
|
ready: boolean;
|
|
125
132
|
open(sessionId: string): void;
|
|
133
|
+
folder: SessionEntryFolder;
|
|
126
134
|
}
|
|
127
135
|
export interface PluginSessionEntry {
|
|
128
136
|
id: string;
|
package/src/runtime-messaging.ts
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
1
1
|
import type { UiText } from "./i18n.ts";
|
|
2
2
|
import type { ProviderSetting, ProviderSettingValues } from "./provider-settings.ts";
|
|
3
3
|
import type { MessagingProviderType, MessagingConnectionInfo, ConversationQuery, ConversationList,
|
|
4
|
-
MessageQuery, MessageList, SendMessage, MessagingMessage, MessagingEvent, ConnectionEvent } from "./messaging.ts";
|
|
4
|
+
MessageQuery, MessageList, SendMessage, MessagingMessage, MessagingEvent, ConnectionEvent, MessagingFileQuery } from "./messaging.ts";
|
|
5
5
|
|
|
6
6
|
export interface MessagingInstance {
|
|
7
7
|
readonly identity: string;
|
|
8
8
|
/**
|
|
9
9
|
* Runs until the receiving signal ends. Call ready once the platform has accepted this receiver; the connection then
|
|
10
|
-
* reports connected and its retry backoff resets. A
|
|
11
|
-
*
|
|
10
|
+
* reports connected and its retry backoff resets. A transport that restores its own protocol session reports
|
|
11
|
+
* reconnecting(error), then ready() after recovery. A rejection is a connection failure: the host calls receive again
|
|
12
|
+
* on the same instance after a backoff unless the error is terminal. Queries and sends have independent request signals.
|
|
12
13
|
*/
|
|
13
|
-
receive(options: { signal: AbortSignal; ready(): void }): Promise<void>;
|
|
14
|
+
receive(options: { signal: AbortSignal; ready(): void; reconnecting(error: unknown): void }): Promise<void>;
|
|
14
15
|
listConversations(query: ConversationQuery, options: { signal: AbortSignal }): Promise<ConversationList>;
|
|
15
16
|
readMessages(query: MessageQuery, options: { signal: AbortSignal }): Promise<MessageList>;
|
|
16
17
|
sendMessage(input: SendMessage, options: { signal: AbortSignal }): Promise<MessagingMessage>;
|
|
18
|
+
openFile?(query: MessagingFileQuery, options: { signal: AbortSignal }): AsyncIterable<Uint8Array>;
|
|
17
19
|
}
|
|
18
20
|
export interface MessagingProviderDefinition {
|
|
19
21
|
id: string;
|
|
@@ -35,6 +37,7 @@ export interface MessagingHandle {
|
|
|
35
37
|
listConversations(query: ConversationQuery, options: { signal: AbortSignal }): Promise<ConversationList>;
|
|
36
38
|
readMessages(query: MessageQuery, options: { signal: AbortSignal }): Promise<MessageList>;
|
|
37
39
|
sendMessage(input: SendMessage, options: { signal: AbortSignal }): Promise<MessagingMessage>;
|
|
40
|
+
openFile(query: MessagingFileQuery, options: { signal: AbortSignal }): AsyncIterable<Uint8Array>;
|
|
38
41
|
}
|
|
39
42
|
export interface MessagingServices {
|
|
40
43
|
types(): readonly MessagingProviderType[];
|
package/src/runtime-sessions.ts
CHANGED
|
@@ -32,5 +32,7 @@ export interface SessionCreation {
|
|
|
32
32
|
(key: string, prepare: (context: SessionPreparation) => Promise<SessionInitialization>, options?: {
|
|
33
33
|
signal?: AbortSignal;
|
|
34
34
|
content?: ContentReader;
|
|
35
|
+
/** Host folder that receives the session; omitted or null leaves it without a folder. A named folder must still exist when the session commits. */
|
|
36
|
+
folderId?: string | null;
|
|
35
37
|
}): Promise<string>;
|
|
36
38
|
}
|
package/src/runtime-web.ts
CHANGED
|
@@ -35,5 +35,6 @@ export interface WebServices {
|
|
|
35
35
|
}
|
|
36
36
|
export type WebErrorCode = "provider_unavailable" | "credential_unavailable" | "unsupported" | "invalid_request" | "protocol" | "request_failed";
|
|
37
37
|
export class WebError extends Error {
|
|
38
|
-
|
|
38
|
+
/** sourceStatus identifies an HTTP failure of the requested page, never the provider API. */
|
|
39
|
+
constructor(readonly code: WebErrorCode, message: string, readonly sourceStatus?: number) { super(message); }
|
|
39
40
|
}
|
package/src/web.ts
CHANGED
|
@@ -4,8 +4,8 @@ import { uiTextSchema } from "./i18n.ts";
|
|
|
4
4
|
import { providerSettingsSchema } from "./provider-settings.ts";
|
|
5
5
|
|
|
6
6
|
export const webUrlSchema = z.string().url().refine(value => {
|
|
7
|
-
const url =
|
|
8
|
-
return ["http:", "https:"].includes(url.protocol) && !url.username && !url.password;
|
|
7
|
+
const url = URL.parse(value);
|
|
8
|
+
return url !== null && ["http:", "https:"].includes(url.protocol) && !url.username && !url.password;
|
|
9
9
|
}, "An HTTP or HTTPS URL without embedded credentials is required.");
|
|
10
10
|
export const webHintSchema = z.object({ code: z.string(), message: z.string(), parameter: z.string().optional() });
|
|
11
11
|
export const webContentPartSchema = z.object({
|