@flowy-agent-store/protocol 0.1.0-beta.10

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/dist/index.cjs ADDED
@@ -0,0 +1,511 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/protocol.ts
3
+ /**
4
+ * Agent Store App Server Protocol types.
5
+ *
6
+ * The chat surface uses only opaque public conversation/message IDs. Internal
7
+ * execution/session/step/attempt IDs never appear in this module.
8
+ */
9
+ /**
10
+ * A contract **fingerprint**, not a version number: it must differ from the
11
+ * previous value on any wire change at all, additive included. The shape is
12
+ * `fp-<n>` — a plain counter, so a bump just increments it and no value is ever
13
+ * reused by accident.
14
+ *
15
+ * So it is a **label, not a version**: neither a release number nor a date.
16
+ * Until `fp-1` the values were date stamps (kept below as history), and those
17
+ * dates were **not** the day of the change: consecutive changes advanced the
18
+ * stamp a day each, so they ran ahead of the calendar. The list below is keyed
19
+ * by *value* — read it as "which wire change is this?", never as "when did this
20
+ * ship".
21
+ *
22
+ * `2026-09-16` carried `StoreItem.published_at`; `2026-09-17` added the two MCP
23
+ * declaration write methods (`config/set-mcp`, `config/set-mcp-enabled`);
24
+ * `2026-09-18` adds `config/get-mcp`, the file editor's read of the same file;
25
+ * `2026-09-19` adds the `conversation/list-changed` notification; `2026-09-20`
26
+ * adds the Skill **file tree** read face (`skill/files`, `skill/file`) so a
27
+ * Skill's companion files are readable, not just its bounded manifest summary;
28
+ * `2026-09-21` adds the connector **call proxy** (`connector/call`), so a third
29
+ * party can run an installed MCP tool while the connection and its credentials
30
+ * stay on the host. **`fp-1` changes the shape only** (date stamp → counter): a
31
+ * `2026-…` value invites being read as a release date, and no wire behaviour
32
+ * changed with the rename. **`fp-2` carries the tools' parameters**
33
+ * (`ConnectorTool.input_schema`, plus `tools_truncated` on `ConnectorDetail`
34
+ * and `ConnectorProbeResult`): a caller that must *name* a tool to be granted it
35
+ * should be able to read what that tool takes. It is the counterpart of the
36
+ * host's `[connector_proxy]` grant moving from one tool at a time to the
37
+ * connector (doc `26`). **`fp-3` makes a Skill selectable per turn**:
38
+ * `conversation/send` gains an optional `mentions` list whose only honoured kind
39
+ * is `skill`, so one turn can mount a Skill's instructions without rewriting the
40
+ * conversation's create-time snapshot (doc `27` 阶段 1). **`fp-4` lets a
41
+ * conversation be created as an installed expert**: `conversation/create` gains
42
+ * an optional `agent_id`, whose Definition supplies the chat's preset identity
43
+ * plus its own Skill and Connector fences — frozen at creation, since none of
44
+ * those keys is mutable afterwards (doc `27` 阶段 2a). **`fp-5` opens a Team's
45
+ * Leader the same way**: an optional `team_id` runs the `team/run` orchestration
46
+ * (members, template, fences) but stops before the goal turn, so the client
47
+ * speaks first; `agent_id` and `team_id` are mutually exclusive (阶段 2b).
48
+ * **`fp-6` makes the model and the reasoning level selectable per call**:
49
+ * `conversation/send` and `agent/run` each gain an optional `model` and
50
+ * `reasoning_effort`. The scope is deliberately the **conversation** (send) and
51
+ * the **run** (agent/run), not "just this turn": the Nomi runtime is built from
52
+ * the persisted row, so a send-carried value is a sticky switch that takes
53
+ * effect on that very turn (doc `29` §4). `ConversationView` also gains
54
+ * `reasoning_effort`, because a setting that can be written by three methods but
55
+ * read back by none is not a setting a client can honour (doc `29` §5.5).
56
+ * **`fp-7` adds the `zip` marketplace source kind**: `market/add` accepts
57
+ * `source_kind: "zip"`, one archive whose root *is* the market root. The
58
+ * official bundles move to it because the old `url` form made a first fetch
59
+ * mirror 14,714 files (611 MiB) for `experts` alone (doc `30`).
60
+ * **`fp-8` adds expert definition export**: `agent/export` and `team/export`
61
+ * return an {@link ExpertPack} — the persona, model hints, skill references and
62
+ * (for a team) the roster with every member expanded. Nothing existing changes
63
+ * shape, but the response carries the Agent Markdown body, which the catalog
64
+ * faces deliberately never do; both methods are WebSocket-only, so the
65
+ * documented route split becomes `48 / 73` (doc `32`).
66
+ * **`fp-13` adds the market policy face** (doc `37`): `market/settings` reads the
67
+ * host's effective sweep cadence, auto-upgrade kind whitelist and last-sweep
68
+ * reading, and `market/settings-set` writes the named keys through to the host's
69
+ * `config.toml`. The same change makes the background sweep able to upgrade
70
+ * entries installed from an `auto_update` market (official sources only, and
71
+ * never a `connector` or a component the user switched off by hand). Both
72
+ * methods are mapped, so the documented route split becomes `55 / 80`.
73
+ * **`fp-14` gives the expert pack its plugin-level assets** (doc `38`):
74
+ * `import/assets` lists the `avatars/`, `bin/` and `scripts/` files of an
75
+ * immutable snapshot (sorted, sha256-digested) and `import/asset` serves one of
76
+ * them base64; `ExpertPack` gains an `assets` list and a declared `avatar` path
77
+ * (`pack_format 2`), so an exported team can materialize a directory the
78
+ * package's own scripts recognize as the plugin root. Both methods are
79
+ * WebSocket-only, so the documented route split becomes `55 / 82`.
80
+ */
81
+ const APP_SERVER_PROTOCOL_VERSION = "fp-14";
82
+ /**
83
+ * Format version of {@link ExpertPack}.
84
+ *
85
+ * **Independent of {@link APP_SERVER_PROTOCOL_VERSION}** on purpose: the
86
+ * fingerprint versions *our* wire compatibility, this versions the **artifact
87
+ * contract for third-party runtimes**. Gate on this one; the fingerprint is
88
+ * about whether your client can talk to the host at all.
89
+ */
90
+ const APP_SERVER_EXPERT_PACK_FORMAT = 2;
91
+ //#endregion
92
+ //#region src/errors.ts
93
+ var AppServerError = class extends Error {
94
+ code;
95
+ requestId;
96
+ retryable;
97
+ details;
98
+ constructor(wire) {
99
+ super(wire.message);
100
+ this.name = "AppServerError";
101
+ this.code = wire.code;
102
+ this.requestId = wire.request_id;
103
+ this.retryable = wire.retryable;
104
+ this.details = wire.details ?? {};
105
+ }
106
+ };
107
+ var TransportError = class extends Error {
108
+ phase;
109
+ retryable;
110
+ cause;
111
+ constructor(phase, message, options) {
112
+ super(message);
113
+ this.name = "TransportError";
114
+ this.phase = phase;
115
+ this.retryable = options?.retryable ?? false;
116
+ this.cause = options?.cause;
117
+ }
118
+ };
119
+ var ProtocolError = class extends Error {
120
+ kind;
121
+ constructor(kind, message) {
122
+ super(message);
123
+ this.name = "ProtocolError";
124
+ this.kind = kind;
125
+ }
126
+ };
127
+ var RequestTimeoutError = class extends Error {
128
+ method;
129
+ timeoutMs;
130
+ constructor(method, timeoutMs) {
131
+ super(`app-server request timed out after ${timeoutMs}ms: ${method}`);
132
+ this.name = "RequestTimeoutError";
133
+ this.method = method;
134
+ this.timeoutMs = timeoutMs;
135
+ }
136
+ };
137
+ function isAppServerError(error) {
138
+ return error instanceof AppServerError;
139
+ }
140
+ function isRetryableTransportError(error) {
141
+ return error instanceof TransportError && error.retryable;
142
+ }
143
+ /**
144
+ * Single human-readable rendering of a caught error.
145
+ *
146
+ * Every UI surface shares this one: a bare `Error` contributes only its
147
+ * message, while a protocol error contributes its stable `code` plus the
148
+ * server's retry hint. Components must not grow their own variants — a
149
+ * second spelling means the two drift apart on the retry hint.
150
+ */
151
+ function formatError(error) {
152
+ if (error instanceof AppServerError) return `${error.code}: ${error.message}`;
153
+ if (error instanceof Error) return error.message;
154
+ return String(error);
155
+ }
156
+ /** Whether the caught error is retryable — used by UI surfaces to append a
157
+ * localized "(可重试)" hint without baking wording into this lib. */
158
+ function isRetryableError(error) {
159
+ return (error instanceof AppServerError || error instanceof TransportError) && error.retryable;
160
+ }
161
+ //#endregion
162
+ //#region src/localized.ts
163
+ /** The other language, i.e. the second link of every fallback chain. */
164
+ function otherLocalizedLang(lang) {
165
+ return lang === "zh" ? "en" : "zh";
166
+ }
167
+ /**
168
+ * Map an i18n language tag (`zh-CN`, `en-US`, `en`) to a variant language.
169
+ * Anything that is not English resolves to `zh`, matching the app default.
170
+ */
171
+ function toLocalizedLang(language) {
172
+ return (language ?? "").toLowerCase().startsWith("en") ? "en" : "zh";
173
+ }
174
+ /** `{field}_{lang}` → `{field}_{other}` → `""`. */
175
+ function pickLocalized(text, lang) {
176
+ if (!text) return "";
177
+ return text[lang]?.trim() || text[otherLocalizedLang(lang)]?.trim() || "";
178
+ }
179
+ /** Resolve a list of localized values, dropping the ones that resolve empty. */
180
+ function pickLocalizedList(list, lang) {
181
+ return (list ?? []).map((item) => pickLocalized(item, lang)).filter((value) => value.length > 0);
182
+ }
183
+ /** Non-empty string variants in fallback order. */
184
+ function variantKeys(field, lang) {
185
+ return [`${field}_${lang}`, `${field}_${otherLocalizedLang(lang)}`];
186
+ }
187
+ /** `{field}_{lang}` → `{field}_{other}` as a string, when either carries text. */
188
+ function pickVariantText(variants, field, lang) {
189
+ for (const key of variantKeys(field, lang)) {
190
+ const value = variants?.[key];
191
+ if (typeof value === "string" && value.trim().length > 0) return value;
192
+ }
193
+ }
194
+ /** `{field}_{lang}` → `{field}_{other}` as a string list, when either is non-empty. */
195
+ function pickVariantList(variants, field, lang) {
196
+ for (const key of variantKeys(field, lang)) {
197
+ const value = variants?.[key];
198
+ if (Array.isArray(value)) {
199
+ const items = value.filter((item) => typeof item === "string" && item.length > 0);
200
+ if (items.length > 0) return items;
201
+ }
202
+ }
203
+ }
204
+ /**
205
+ * Market entry tags. Per D8=A `tags_{lang}` outranks `legacy_tags_{lang}` —
206
+ * the legacy field only fills in when the current one is absent, in either
207
+ * language.
208
+ */
209
+ function pickEntryTags(variants, lang) {
210
+ return pickVariantList(variants, "tags", lang) ?? pickVariantList(variants, "legacy_tags", lang);
211
+ }
212
+ /**
213
+ * A market entry text field: variant first, then the baseline field
214
+ * (`entry.description`, `entry.name`, …) as the last link of the chain.
215
+ */
216
+ function pickEntryText(variants, field, lang, baseline) {
217
+ return pickVariantText(variants, field, lang) ?? baseline ?? void 0;
218
+ }
219
+ //#endregion
220
+ //#region src/conversation-events.ts
221
+ function stringValue(value) {
222
+ return typeof value === "string" ? value : null;
223
+ }
224
+ function numberValue(value) {
225
+ return typeof value === "number" ? value : null;
226
+ }
227
+ function isRecord(value) {
228
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
229
+ }
230
+ /**
231
+ * Strict boolean reader: a wire value that is not a real boolean reads as
232
+ * `null` (unknown) rather than being coerced — "retryable" must never be
233
+ * guessed from a truthy string.
234
+ */
235
+ function booleanValue(value) {
236
+ return typeof value === "boolean" ? value : null;
237
+ }
238
+ /** Flatten a message/activity body to plain text, JSON-encoding anything else. */
239
+ function contentToText(value) {
240
+ if (typeof value === "string") return value;
241
+ if (isRecord(value) && typeof value.content === "string") return value.content;
242
+ return value == null ? "" : JSON.stringify(value);
243
+ }
244
+ /** Activity bodies may be nested one level down or JSON-encoded as a string. */
245
+ function unwrapContent(value) {
246
+ if (typeof value === "string") try {
247
+ return JSON.parse(value);
248
+ } catch {
249
+ return value;
250
+ }
251
+ if (isRecord(value)) {
252
+ const content = value.content;
253
+ if (typeof content === "string") try {
254
+ return JSON.parse(content);
255
+ } catch {
256
+ return value;
257
+ }
258
+ }
259
+ return value;
260
+ }
261
+ /** Shape a thinking body (`message.thinking`, or `message.activity` kind `thinking`). */
262
+ function thinkingData(value) {
263
+ if (isRecord(value) && typeof value.content === "string") return {
264
+ content: value.content,
265
+ subject: stringValue(value.subject),
266
+ status: stringValue(value.status),
267
+ duration: numberValue(value.duration) ?? numberValue(value.duration_ms)
268
+ };
269
+ const candidate = unwrapContent(value);
270
+ if (!isRecord(candidate)) return {
271
+ content: typeof candidate === "string" ? candidate : "",
272
+ subject: null,
273
+ status: null,
274
+ duration: null
275
+ };
276
+ return {
277
+ content: stringValue(candidate.content) ?? "",
278
+ subject: stringValue(candidate.subject),
279
+ status: stringValue(candidate.status),
280
+ duration: numberValue(candidate.duration) ?? numberValue(candidate.duration_ms)
281
+ };
282
+ }
283
+ /** Shape a tips body; `type` is accepted as an alias of `tip_type`. */
284
+ function tipsData(value) {
285
+ const readTip = (data) => {
286
+ const content = stringValue(data.content);
287
+ const tipType = stringValue(data.tip_type) ?? stringValue(data.type);
288
+ if (content === null && tipType === null) return null;
289
+ return {
290
+ content: content ?? "",
291
+ tipType: tipType ?? "info"
292
+ };
293
+ };
294
+ if (isRecord(value)) {
295
+ const direct = readTip(value);
296
+ if (direct) return direct;
297
+ }
298
+ const candidate = unwrapContent(value);
299
+ if (isRecord(candidate)) {
300
+ const parsed = readTip(candidate);
301
+ if (parsed) return parsed;
302
+ }
303
+ if (candidate != null && !isRecord(candidate)) return {
304
+ content: String(candidate),
305
+ tipType: "info"
306
+ };
307
+ return {
308
+ content: "",
309
+ tipType: "info"
310
+ };
311
+ }
312
+ /** Shape a tool-call body; `null` when the body carries nothing tool-shaped. */
313
+ function toolCallData(value) {
314
+ const candidate = unwrapContent(value);
315
+ if (!isRecord(candidate)) return null;
316
+ const name = stringValue(candidate.name) ?? stringValue(candidate.tool_name) ?? stringValue(candidate.tool);
317
+ if (!name && candidate.args === void 0 && candidate.arguments === void 0 && candidate.output === void 0 && candidate.result === void 0) return null;
318
+ return {
319
+ name,
320
+ args: candidate.args ?? candidate.arguments ?? candidate.input,
321
+ output: candidate.output ?? candidate.result,
322
+ status: stringValue(candidate.status)
323
+ };
324
+ }
325
+ /**
326
+ * Shape a plan body; `null` when there is no usable step list.
327
+ *
328
+ * `step` is accepted as an alias of `content`: the tool's own argument is named
329
+ * `step`, and the producer normalizes it to `content` for the plan row — a row
330
+ * written before that normalization (or by a producer that skipped it) would
331
+ * otherwise render as an empty plan.
332
+ */
333
+ function planData(value) {
334
+ const candidate = unwrapContent(value);
335
+ if (!isRecord(candidate) || !Array.isArray(candidate.entries)) return null;
336
+ const entries = candidate.entries.flatMap((raw) => {
337
+ if (!isRecord(raw)) return [];
338
+ const content = stringValue(raw.content) ?? stringValue(raw.step);
339
+ if (!content) return [];
340
+ return [{
341
+ content,
342
+ status: planStepStatus(raw.status)
343
+ }];
344
+ });
345
+ return entries.length > 0 ? { entries } : null;
346
+ }
347
+ /** Unknown/absent step statuses read as `pending` — never as "done". */
348
+ function planStepStatus(value) {
349
+ return value === "completed" || value === "in_progress" ? value : "pending";
350
+ }
351
+ /** Shape a `context.usage` payload; `null` when nothing was actually measured. */
352
+ function parseContextUsage(value) {
353
+ if (!isRecord(value)) return null;
354
+ const used = typeof value.used_tokens === "number" ? value.used_tokens : 0;
355
+ const window = typeof value.window_tokens === "number" ? value.window_tokens : 0;
356
+ if (used <= 0 || window <= 0) return null;
357
+ const rawPercent = typeof value.percent === "number" ? value.percent : used / window * 100;
358
+ return {
359
+ used_tokens: used,
360
+ window_tokens: window,
361
+ percent: Math.min(100, Math.max(0, rawPercent)),
362
+ updated_at: typeof value.updated_at === "number" ? value.updated_at : Date.now(),
363
+ source: typeof value.source === "string" ? value.source : "measured"
364
+ };
365
+ }
366
+ /**
367
+ * Shape a per-turn `usage` body (W9 / R14); `null` when the runtime reported
368
+ * nothing usable.
369
+ *
370
+ * A missing side is **unknown**, not zero: half a bill is not a bill, so a
371
+ * frame that only carries `input_tokens` decodes to `null` rather than to a
372
+ * total that silently drops the output side. Same rule for an all-zero report —
373
+ * "no tokens reported" must never render as "this turn was free".
374
+ */
375
+ function parseTurnUsage(value) {
376
+ if (!isRecord(value)) return null;
377
+ const input = typeof value.input_tokens === "number" ? value.input_tokens : null;
378
+ const output = typeof value.output_tokens === "number" ? value.output_tokens : null;
379
+ if (input === null || output === null) return null;
380
+ if (input <= 0 && output <= 0) return null;
381
+ return {
382
+ input_tokens: input,
383
+ output_tokens: output,
384
+ total_tokens: typeof value.total_tokens === "number" ? value.total_tokens : input + output
385
+ };
386
+ }
387
+ /**
388
+ * Decode one `conversation/event` frame into a typed body.
389
+ *
390
+ * An activity frame whose `kind` is `thinking` is normalized to
391
+ * `message.thinking` (the server has two spellings for the same thing).
392
+ */
393
+ function decodeConversationEvent(event) {
394
+ const payload = event.payload ?? {};
395
+ const messageId = () => stringValue(payload.message_id);
396
+ const createdAt = () => numberValue(payload.created_at);
397
+ if (event.event_type === "message.activity" && stringValue(payload.kind) === "thinking") return {
398
+ kind: "message.thinking",
399
+ event,
400
+ messageId: messageId(),
401
+ createdAt: createdAt(),
402
+ thinking: thinkingData(payload),
403
+ replace: payload.replace === true
404
+ };
405
+ switch (event.event_type) {
406
+ case "message.created": return {
407
+ kind: "message.created",
408
+ event,
409
+ messageId: messageId(),
410
+ createdAt: createdAt(),
411
+ content: payload.content ?? ""
412
+ };
413
+ case "message.delta": return {
414
+ kind: "message.delta",
415
+ event,
416
+ messageId: messageId(),
417
+ createdAt: createdAt(),
418
+ delta: stringValue(payload.content) ?? "",
419
+ replace: payload.replace === true
420
+ };
421
+ case "message.thinking": return {
422
+ kind: "message.thinking",
423
+ event,
424
+ messageId: messageId(),
425
+ createdAt: createdAt(),
426
+ thinking: thinkingData(payload),
427
+ replace: payload.replace === true
428
+ };
429
+ case "message.tool": return {
430
+ kind: "message.tool",
431
+ event,
432
+ messageId: messageId(),
433
+ createdAt: createdAt(),
434
+ tool: toolCallData(payload)
435
+ };
436
+ case "message.tips": return {
437
+ kind: "message.tips",
438
+ event,
439
+ messageId: messageId(),
440
+ createdAt: createdAt(),
441
+ tips: tipsData(payload)
442
+ };
443
+ case "message.error": return {
444
+ kind: "message.error",
445
+ event,
446
+ messageId: messageId(),
447
+ createdAt: createdAt(),
448
+ message: stringValue(payload.message),
449
+ code: stringValue(payload.code),
450
+ retryable: booleanValue(payload.retryable)
451
+ };
452
+ case "message.activity": {
453
+ const activityKind = stringValue(payload.kind) ?? "activity";
454
+ return {
455
+ kind: "message.activity",
456
+ event,
457
+ messageId: messageId(),
458
+ createdAt: createdAt(),
459
+ activityKind,
460
+ content: payload.content ?? "",
461
+ usage: activityKind === "turn_completed" ? parseTurnUsage(payload.usage) : null
462
+ };
463
+ }
464
+ case "turn.status": return {
465
+ kind: "turn.status",
466
+ event,
467
+ running: stringValue(payload.status) === "running"
468
+ };
469
+ case "context.usage": return {
470
+ kind: "context.usage",
471
+ event,
472
+ usage: parseContextUsage(payload.context_usage)
473
+ };
474
+ default: return {
475
+ kind: "unknown",
476
+ event,
477
+ eventType: event.event_type
478
+ };
479
+ }
480
+ }
481
+ //#endregion
482
+ exports.APP_SERVER_EXPERT_PACK_FORMAT = APP_SERVER_EXPERT_PACK_FORMAT;
483
+ exports.APP_SERVER_PROTOCOL_VERSION = APP_SERVER_PROTOCOL_VERSION;
484
+ exports.AppServerError = AppServerError;
485
+ exports.ProtocolError = ProtocolError;
486
+ exports.RequestTimeoutError = RequestTimeoutError;
487
+ exports.TransportError = TransportError;
488
+ exports.booleanValue = booleanValue;
489
+ exports.contentToText = contentToText;
490
+ exports.decodeConversationEvent = decodeConversationEvent;
491
+ exports.formatError = formatError;
492
+ exports.isAppServerError = isAppServerError;
493
+ exports.isRecord = isRecord;
494
+ exports.isRetryableError = isRetryableError;
495
+ exports.isRetryableTransportError = isRetryableTransportError;
496
+ exports.numberValue = numberValue;
497
+ exports.otherLocalizedLang = otherLocalizedLang;
498
+ exports.parseContextUsage = parseContextUsage;
499
+ exports.parseTurnUsage = parseTurnUsage;
500
+ exports.pickEntryTags = pickEntryTags;
501
+ exports.pickEntryText = pickEntryText;
502
+ exports.pickLocalized = pickLocalized;
503
+ exports.pickLocalizedList = pickLocalizedList;
504
+ exports.pickVariantList = pickVariantList;
505
+ exports.pickVariantText = pickVariantText;
506
+ exports.planData = planData;
507
+ exports.stringValue = stringValue;
508
+ exports.thinkingData = thinkingData;
509
+ exports.tipsData = tipsData;
510
+ exports.toLocalizedLang = toLocalizedLang;
511
+ exports.toolCallData = toolCallData;