@syengup/fridaynext-hermes-channel 0.1.0-beta.2 → 0.1.0-beta.4

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.
Files changed (92) hide show
  1. package/README.md +2 -2
  2. package/install-config.js +67 -0
  3. package/install-runtime.js +18 -9
  4. package/install.js +6 -4
  5. package/package.json +2 -1
  6. package/plugin/README.md +2 -2
  7. package/plugin/fridaynext_plugin/__init__.py +10 -0
  8. package/plugin/fridaynext_plugin/adapter.py +231 -12
  9. package/plugin/fridaynext_plugin/agent_management.py +158 -0
  10. package/plugin/fridaynext_plugin/canonical_control.py +12 -4
  11. package/plugin/fridaynext_plugin/compat_v0225.py +1247 -4
  12. package/plugin/fridaynext_plugin/continuations.py +271 -0
  13. package/plugin/fridaynext_plugin/device-tools-v1.json +302 -0
  14. package/plugin/fridaynext_plugin/device_tools.py +144 -0
  15. package/plugin/fridaynext_plugin/history.py +25 -3
  16. package/plugin/fridaynext_plugin/host.py +7 -4
  17. package/plugin/fridaynext_plugin/media_input.py +56 -9
  18. package/plugin/fridaynext_plugin/message_speech.py +143 -0
  19. package/plugin/fridaynext_plugin/multi_agent.py +221 -0
  20. package/plugin/fridaynext_plugin/reply_context.py +39 -0
  21. package/plugin/fridaynext_plugin/runtime_port.py +23 -1
  22. package/plugin/fridaynext_plugin/scheduled_tasks.py +229 -0
  23. package/plugin/fridaynext_plugin/settings.py +7 -3
  24. package/plugin/fridaynext_plugin/slash_commands.py +163 -0
  25. package/plugin/fridaynext_plugin/stream_bridge.py +83 -26
  26. package/plugin/fridaynext_plugin/stream_projection.py +30 -6
  27. package/plugin/fridaynext_plugin/subagents.py +228 -0
  28. package/plugin/plugin.yaml +11 -0
  29. package/plugin/runtime/dist/commands-routes.js +94 -0
  30. package/plugin/runtime/dist/device-tools-v1.json +302 -0
  31. package/plugin/runtime/dist/hosted-backend.js +293 -25
  32. package/plugin/runtime/dist/hosted-continuations.js +41 -0
  33. package/plugin/runtime/dist/hosted-device-tools.js +82 -0
  34. package/plugin/runtime/dist/hosted-media.js +54 -13
  35. package/plugin/runtime/dist/hosted-stream.js +124 -14
  36. package/plugin/runtime/dist/hosted-subagents.js +78 -0
  37. package/plugin/runtime/dist/platform-service.js +4 -0
  38. package/plugin/runtime/dist/plugin-control.js +10 -6
  39. package/plugin/runtime/dist/scheduled-routes.js +63 -0
  40. package/plugin/runtime/dist/service-host.js +40 -5
  41. package/plugin/runtime/dist/speech-routes.js +111 -0
  42. package/plugin/runtime/dist/tool-presentation.js +399 -0
  43. package/plugin/runtime/node_modules/.package-lock.json +6 -6
  44. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/API.md +125 -5
  45. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/README.md +21 -1
  46. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/history.d.ts +1 -0
  47. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/history.js +3 -0
  48. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/operations.d.ts +136 -0
  49. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/operations.js +105 -0
  50. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/settings-schema.d.ts +3 -0
  51. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/settings-schema.js +45 -0
  52. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/tool-presentation.d.ts +10 -0
  53. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/tool-presentation.js +2 -0
  54. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/types.d.ts +27 -2
  55. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/types.js +1 -0
  56. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/work-context.d.ts +56 -0
  57. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/work-context.js +60 -0
  58. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/device-request/pending-store.js +3 -3
  59. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/index.d.ts +5 -0
  60. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/index.js +5 -0
  61. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/canonical-update-batcher.d.ts +26 -0
  62. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/canonical-update-batcher.js +112 -0
  63. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/channel-kernel.d.ts +4 -1
  64. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/channel-kernel.js +30 -5
  65. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/durable-run-store.d.ts +18 -1
  66. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/durable-run-store.js +187 -51
  67. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/runner.d.ts +1 -0
  68. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/runner.js +52 -2
  69. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/work-context.d.ts +13 -0
  70. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/work-context.js +73 -0
  71. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/service/channel-service.js +1 -1
  72. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/command-lifecycle.d.ts +47 -0
  73. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/command-lifecycle.js +184 -0
  74. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/controls.d.ts +1 -1
  75. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/controls.js +11 -0
  76. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/messages.js +12 -6
  77. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/operations.d.ts +13 -0
  78. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/operations.js +336 -0
  79. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/runtime.d.ts +1 -0
  80. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/runtime.js +52 -10
  81. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/session-settings.js +38 -6
  82. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/sessions.js +8 -8
  83. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/package.json +6 -7
  84. package/plugin/runtime/node_modules/tslib/README.md +3 -8
  85. package/plugin/runtime/node_modules/tslib/package.json +1 -1
  86. package/plugin/runtime/node_modules/tslib/tslib.d.ts +4 -2
  87. package/plugin/runtime/node_modules/tslib/tslib.es6.js +10 -1
  88. package/plugin/runtime/node_modules/tslib/tslib.es6.mjs +10 -1
  89. package/plugin/runtime/node_modules/tslib/tslib.js +10 -1
  90. package/plugin/runtime/package-lock.json +7 -7
  91. package/plugin/runtime/package.json +1 -1
  92. package/plugin/tools.py +3 -0
@@ -0,0 +1,336 @@
1
+ import { ChannelError, } from "../contract/types.js";
2
+ import { BACKEND_OPERATIONS_V1, operationDefinition, operationObject, validOperationInput, } from "../contract/operations.js";
3
+ import { readJsonBody } from "./body.js";
4
+ import { WORKSPACE_PHASES, sameWorkContext, sameWorkspace, validWorkContextIdentity, validWorkContextSnapshot, validWorkContextTransaction, validWorkspaceCompletion, workspaceOperation } from "../contract/work-context.js";
5
+ import { hasWorkContext, pendingWorkspaceCommand, readWorkContext, workContextCapabilityAllowed } from "../runtime/work-context.js";
6
+ const identity = (value) => typeof value === "string" && !!value.trim();
7
+ const kind = "backend-operation-v1";
8
+ export function createOperationHandler(store, adapter, policy) {
9
+ const submissions = new Map();
10
+ const reply = (res, status, value) => {
11
+ res.statusCode = status;
12
+ res.setHeader("Content-Type", "application/json");
13
+ res.setHeader("Cache-Control", "no-store");
14
+ res.end(JSON.stringify(value));
15
+ return true;
16
+ };
17
+ function supported(definition) {
18
+ return (adapter.operations?.version === 1 &&
19
+ adapter.descriptor.capabilities.includes(BACKEND_OPERATIONS_V1) &&
20
+ adapter.descriptor.capabilities.includes(definition.capability) &&
21
+ typeof adapter.operations.ports[definition.id]?.execute === "function");
22
+ }
23
+ function allowed(definition, context) {
24
+ const details = adapter.descriptor.capabilityDetails;
25
+ if (!details)
26
+ return true;
27
+ if (details.version !== 1)
28
+ return false;
29
+ const constraint = details.capabilities[definition.capability];
30
+ if (!constraint)
31
+ return true;
32
+ return ((constraint.permission === undefined ||
33
+ constraint.permission === "allowed") &&
34
+ (constraint.sessionKey === undefined ||
35
+ constraint.sessionKey === context.sessionKey) &&
36
+ (constraint.scope === undefined ||
37
+ ["service", "session", "device"].includes(constraint.scope)) &&
38
+ (constraint.scope !== "session" || !!context.sessionKey) &&
39
+ (constraint.scope !== "device" || identity(context.deviceId)));
40
+ }
41
+ function checked(value) {
42
+ if (!operationObject(value) ||
43
+ !["applied", "conflict", "unknown"].includes(String(value.status)) ||
44
+ (value.status === "applied" && !operationObject(value.value)) ||
45
+ (value.value !== undefined && !operationObject(value.value)) ||
46
+ (value.code !== undefined && typeof value.code !== "string"))
47
+ throw Error("invalid_operation_result");
48
+ if (value.status === "applied")
49
+ return { status: "applied", value: value.value };
50
+ const code = typeof value.code === "string" ? { code: value.code } : {};
51
+ return value.status === "conflict"
52
+ ? {
53
+ status: "conflict",
54
+ ...code,
55
+ ...(value.value ? { value: value.value } : {}),
56
+ }
57
+ : { status: "unknown", ...code };
58
+ }
59
+ return async (req, res) => {
60
+ const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
61
+ if (pathname !== "/friday-next/operations" &&
62
+ !pathname.startsWith("/friday-next/operations/"))
63
+ return false;
64
+ const base = { version: 1, serverInstanceId: store.serverInstanceId };
65
+ if (pathname === "/friday-next/operations") {
66
+ if (req.method !== "GET")
67
+ return reply(res, 405, { code: "METHOD_NOT_ALLOWED" });
68
+ if (adapter.operations?.version !== 1 ||
69
+ !adapter.descriptor.capabilities.includes(BACKEND_OPERATIONS_V1))
70
+ return reply(res, 404, { code: "UNSUPPORTED_CAPABILITY" });
71
+ const definitions = Object.keys(adapter.operations.ports)
72
+ .map(operationDefinition)
73
+ .filter((d) => !!d && supported(d))
74
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
75
+ return reply(res, 200, { ...base, operations: definitions });
76
+ }
77
+ if (req.method !== "POST")
78
+ return reply(res, 405, { code: "METHOD_NOT_ALLOWED" });
79
+ let id;
80
+ try {
81
+ id = decodeURIComponent(pathname.slice("/friday-next/operations/".length));
82
+ }
83
+ catch {
84
+ return reply(res, 400, { code: "INVALID_OPERATION" });
85
+ }
86
+ const definition = operationDefinition(id);
87
+ if (!definition)
88
+ return reply(res, 404, { code: "UNSUPPORTED_OPERATION" });
89
+ let body;
90
+ try {
91
+ const input = await readJsonBody(req);
92
+ if (!operationObject(input))
93
+ throw Error();
94
+ body = input;
95
+ }
96
+ catch {
97
+ return reply(res, 400, { code: "INVALID_OPERATION_INPUT" });
98
+ }
99
+ if (body.version !== 1)
100
+ return reply(res, 426, { code: "UNSUPPORTED_OPERATION_VERSION" });
101
+ if (body.expectedServerInstanceId !== store.serverInstanceId)
102
+ return reply(res, 409, { ...base, code: "SERVICE_IDENTITY_CHANGED" });
103
+ if (Object.keys(body).some((k) => ![
104
+ "version",
105
+ "expectedServerInstanceId",
106
+ "deviceId",
107
+ "sessionKey",
108
+ "agentId",
109
+ "commandId",
110
+ "input",
111
+ "workContext",
112
+ ].includes(k)) ||
113
+ (body.workContext !== undefined && !validWorkContextIdentity(body.workContext)) ||
114
+ !validOperationInput(definition.id, body.input) ||
115
+ ["sessionKey", "agentId", "commandId", "deviceId"].some((k) => body[k] !== undefined && !identity(body[k])))
116
+ return reply(res, 400, { code: "INVALID_OPERATION_INPUT" });
117
+ const context = {
118
+ serviceInstanceId: store.serverInstanceId,
119
+ ...(validWorkContextIdentity(body.workContext) ? { workContext: body.workContext } : {}),
120
+ ...(typeof body.sessionKey === "string"
121
+ ? { sessionKey: body.sessionKey }
122
+ : {}),
123
+ ...(typeof body.agentId === "string" ? { agentId: body.agentId } : {}),
124
+ };
125
+ let actual;
126
+ try {
127
+ actual = policy.operationIdentity?.(req);
128
+ }
129
+ catch {
130
+ return reply(res, 403, { code: "OPERATION_FORBIDDEN" });
131
+ }
132
+ if (actual)
133
+ context.deviceId = actual.deviceId;
134
+ if (body.deviceId !== undefined && body.deviceId !== context.deviceId)
135
+ return reply(res, 403, { code: "DEVICE_IDENTITY_MISMATCH" });
136
+ // 不存在端口时仍允许带原命令身份的回执核对,其余请求直接明确不可用。
137
+ if (!supported(definition) &&
138
+ (!definition.mutating ||
139
+ !identity(context.deviceId) ||
140
+ !identity(body.commandId)))
141
+ return reply(res, 404, { code: "UNSUPPORTED_OPERATION" });
142
+ if ((definition.scope === "session" && !context.sessionKey) ||
143
+ (definition.scope === "agent" && !context.agentId) ||
144
+ ((definition.scope === "device" || definition.mutating) &&
145
+ !identity(context.deviceId)) ||
146
+ (definition.mutating && !identity(body.commandId)))
147
+ return reply(res, 400, { code: "INVALID_OPERATION_IDENTITY" });
148
+ let authorized = false;
149
+ try {
150
+ authorized =
151
+ allowed(definition, context) &&
152
+ (!policy.authorizeOperation ||
153
+ (await policy.authorizeOperation(req, definition.id)));
154
+ }
155
+ catch {
156
+ /* 无法证明权限时不执行宿主操作。 */
157
+ }
158
+ if (!authorized)
159
+ return reply(res, 403, { code: "OPERATION_FORBIDDEN" });
160
+ const port = adapter.operations?.version === 1
161
+ ? adapter.operations.ports[definition.id]
162
+ : undefined;
163
+ // 已经通过对应id的输入校验;关联类型仅在这一个公共分派边界擦除。
164
+ const execute = port?.execute.bind(port);
165
+ const inspect = port?.inspect?.bind(port);
166
+ const input = body.input;
167
+ const lifecycle = workspaceOperation(id);
168
+ const checkedForCommand = (value, inspecting = false) => {
169
+ const result = checked(value);
170
+ const progress = lifecycle ? store.commandReceipt(kind, key)?.context?.progress : undefined;
171
+ // 拿到租约后的冲突不能证明回滚;没有原事务结算证据时继续冻结。
172
+ if (lifecycle && result.status === "conflict" && (!validWorkContextTransaction(progress) || progress.phase !== "prepared"))
173
+ throw Error("workspace_conflict_requires_reconciliation");
174
+ if (lifecycle && result.status === "applied") {
175
+ const transaction = result.value.transaction, snapshot = result.value.workContext;
176
+ const target = body.input && operationObject(body.input) && body.input.target;
177
+ if (!validWorkContextTransaction(transaction) || transaction.commandId !== context.commandId || transaction.operationId !== id
178
+ || !context.workContext || !sameWorkContext(transaction.source, context.workContext) || transaction.phase !== "completed"
179
+ || !validWorkContextTransaction(progress) || !progress.leaseRef || progress.leaseRef !== transaction.leaseRef
180
+ || (!inspecting && progress.phase !== "completed")
181
+ || (target === undefined ? transaction.target !== undefined : !validWorkContextIdentity(target) || !transaction.target || !sameWorkContext(transaction.target, target))
182
+ || !validWorkContextSnapshot(snapshot) || snapshot.version !== 1
183
+ || !sameWorkspace(snapshot, validWorkContextIdentity(target) ? target : context.workContext)
184
+ || !validWorkspaceCompletion(id, snapshot, result.value.restoration)
185
+ || (id !== "workspace.archive" && snapshot.contextVersion === context.workContext.contextVersion))
186
+ throw Error("invalid_work_context_result");
187
+ if (inspecting && progress.phase !== "completed")
188
+ store.checkpointCommandReceipt(kind, key, payload, transaction);
189
+ }
190
+ return result;
191
+ };
192
+ if (!definition.mutating) {
193
+ if (!supported(definition) || !execute)
194
+ return reply(res, 404, { code: "UNSUPPORTED_OPERATION" });
195
+ try {
196
+ const value = await execute(context, input);
197
+ if (!operationObject(value))
198
+ throw Error();
199
+ return reply(res, 200, { ...base, operationId: id, value });
200
+ }
201
+ catch (error) {
202
+ return reply(res, error instanceof ChannelError ? error.status : 503, {
203
+ ...base,
204
+ operationId: id,
205
+ code: error instanceof ChannelError
206
+ ? error.code
207
+ : "OPERATION_UNAVAILABLE",
208
+ });
209
+ }
210
+ }
211
+ context.commandId = body.commandId;
212
+ const key = JSON.stringify([
213
+ store.serverInstanceId,
214
+ context.deviceId,
215
+ context.commandId,
216
+ ]);
217
+ const payload = { ...body, operationId: id, deviceId: context.deviceId };
218
+ const envelope = (value) => ({
219
+ ...base,
220
+ operationId: id,
221
+ commandId: context.commandId,
222
+ ...value,
223
+ });
224
+ const send = (value) => reply(res, value.status === "applied"
225
+ ? 200
226
+ : value.status === "conflict"
227
+ ? 409
228
+ : 503, value);
229
+ const previous = submissions.get(key) ?? Promise.resolve();
230
+ let release;
231
+ const held = new Promise((resolve) => {
232
+ release = resolve;
233
+ });
234
+ submissions.set(key, held);
235
+ await previous.catch(() => { });
236
+ try {
237
+ const status = store.commandReceiptStatus(kind, key, payload);
238
+ if (status === "conflict")
239
+ return reply(res, 409, { code: "COMMAND_CONFLICT" });
240
+ if (status === "replayed")
241
+ return send({
242
+ ...store.commandReceipt(kind, key).response,
243
+ replayed: true,
244
+ });
245
+ if (status === "prepared") {
246
+ const progress = store.commandReceipt(kind, key)?.context?.progress;
247
+ if (lifecycle && validWorkContextTransaction(progress))
248
+ context.transaction = structuredClone(progress);
249
+ let result;
250
+ try {
251
+ result = checkedForCommand((await inspect?.(context, input)) ?? { status: "unknown" }, true);
252
+ }
253
+ catch {
254
+ result = { status: "unknown", code: "OPERATION_UNAVAILABLE" };
255
+ }
256
+ const value = envelope(result);
257
+ if (result.status !== "unknown")
258
+ store.completeCommandReceipt(kind, key, payload, value);
259
+ return send(value);
260
+ }
261
+ if (!supported(definition) || !execute)
262
+ return reply(res, 404, { code: "UNSUPPORTED_OPERATION" });
263
+ if (lifecycle) {
264
+ if (!context.workContext || !workContextCapabilityAllowed(adapter, context.sessionKey))
265
+ return reply(res, 404, { code: "UNSUPPORTED_WORK_CONTEXT" });
266
+ const current = await readWorkContext(adapter, store, context.sessionKey);
267
+ if (current.version !== 1 || !sameWorkContext(current, context.workContext))
268
+ return reply(res, 409, { code: "WORK_CONTEXT_CONFLICT" });
269
+ const states = id === "workspace.create" ? ["draft", "bound"] : id === "workspace.restore" ? ["archived"] : ["bound"];
270
+ if (!states.includes(current.state) || current.transaction && current.transaction.phase !== "completed")
271
+ return reply(res, 409, { code: "WORK_CONTEXT_NOT_WRITABLE" });
272
+ const target = operationObject(input.target) ? input.target : undefined;
273
+ if (target && (!validWorkContextIdentity(target) || target.serverInstanceId !== store.serverInstanceId || target.hostScopeRef !== context.workContext.hostScopeRef))
274
+ return reply(res, 409, { code: "WORK_CONTEXT_CONFLICT" });
275
+ const affected = [context.workContext, ...(validWorkContextIdentity(target) ? [target] : [])];
276
+ const independentSource = id === "workspace.create"
277
+ && adapter.operations?.ports["workspace.create"]?.sourceRunPolicy === "independent"
278
+ && validWorkContextIdentity(target) && !sameWorkspace(context.workContext, target);
279
+ if (affected.some(value => pendingWorkspaceCommand(store, value)) || store.runs().some(run => {
280
+ if (["completed", "failed", "cancelled"].includes(run.phase))
281
+ return false;
282
+ const identity = run.sessionOptions?.workContext;
283
+ // 独立源只放行已知活动,目标占用与未知对账仍按原事务阻断。
284
+ if (validWorkContextIdentity(target) && validWorkContextIdentity(identity) && sameWorkspace(identity, target))
285
+ return true;
286
+ const sourceRun = run.sessionKey === context.sessionKey || validWorkContextIdentity(identity) && sameWorkspace(identity, context.workContext);
287
+ return sourceRun && (!independentSource || !["queued", "dispatching", "running", "waitingForApproval", "waitingForDevice", "cancelPending"].includes(run.phase));
288
+ }))
289
+ return reply(res, 409, { code: "WORK_CONTEXT_BUSY" });
290
+ }
291
+ else if (hasWorkContext(adapter) && ["agent.configure", "agent.write-file"].includes(id) && port?.workContextEffect !== "preserve") {
292
+ return reply(res, 409, { code: "WORK_CONTEXT_MIGRATION_REQUIRED" });
293
+ }
294
+ store.prepareCommandReceipt(kind, key, payload, {
295
+ request: payload,
296
+ operationId: id,
297
+ });
298
+ if (lifecycle) {
299
+ const transaction = { version: 1, commandId: context.commandId, operationId: id, source: context.workContext,
300
+ ...(validWorkContextIdentity(input.target) ? { target: input.target } : {}), phase: "prepared" };
301
+ store.checkpointCommandReceipt(kind, key, payload, transaction);
302
+ context.checkpoint = (phase, leaseRef) => {
303
+ const previous = store.commandReceipt(kind, key).context.progress;
304
+ if (!WORKSPACE_PHASES.includes(phase) || WORKSPACE_PHASES.indexOf(phase) < WORKSPACE_PHASES.indexOf(previous.phase)
305
+ || (previous.leaseRef !== undefined && leaseRef !== undefined && previous.leaseRef !== leaseRef))
306
+ throw Error("invalid_workspace_checkpoint");
307
+ const next = { ...previous, phase, ...(leaseRef !== undefined ? { leaseRef } : {}) };
308
+ if (phase !== "prepared" && (typeof next.leaseRef !== "string" || !next.leaseRef.trim()))
309
+ throw Error("missing_workspace_lease");
310
+ store.checkpointCommandReceipt(kind, key, payload, next);
311
+ };
312
+ }
313
+ let result;
314
+ try {
315
+ result = checkedForCommand(await execute(context, input));
316
+ }
317
+ catch {
318
+ result = { status: "unknown", code: "OPERATION_UNAVAILABLE" };
319
+ }
320
+ const value = envelope(result);
321
+ if (result.status !== "unknown")
322
+ store.completeCommandReceipt(kind, key, payload, value);
323
+ return send(value);
324
+ }
325
+ catch (error) {
326
+ if (error instanceof ChannelError)
327
+ return reply(res, error.status, { ...base, operationId: id, commandId: context.commandId, code: error.code });
328
+ return send(envelope({ status: "unknown", code: "OPERATION_UNAVAILABLE" }));
329
+ }
330
+ finally {
331
+ release();
332
+ if (submissions.get(key) === held)
333
+ submissions.delete(key);
334
+ }
335
+ };
336
+ }
@@ -46,5 +46,6 @@ export declare function createRuntimeTransport(deps: RuntimeTransportDependencie
46
46
  handleRuntimeV3Sync: (req: IncomingMessage, res: ServerResponse) => Promise<boolean>;
47
47
  handleRuntimeV3SessionSnapshot: (req: IncomingMessage, res: ServerResponse, sessionKey: string, identityAttempt?: number) => Promise<boolean>;
48
48
  handleRuntimeV3Cancel: (req: IncomingMessage, res: ServerResponse, runId: string) => Promise<boolean>;
49
+ handleQueuedMessageDelete: (req: IncomingMessage, res: ServerResponse, runId: string) => Promise<boolean>;
49
50
  };
50
51
  export {};
@@ -3,6 +3,7 @@ import { canonicalPayload, isCanonicalPayload } from "../contract/types.js";
3
3
  import { assertHistorySnapshotV1 } from "../contract/history.js";
4
4
  import { ChannelError } from "../contract/types.js";
5
5
  import { readJsonBody } from "./body.js";
6
+ import { validWorkContextIdentity, workContextIdentity } from "../contract/work-context.js";
6
7
  // 每个后端上下文独立创建协议处理器,所有宿主能力显式注入。
7
8
  export function createRuntimeTransport(deps) {
8
9
  const logger = deps.logger ?? { info() { }, warn() { } };
@@ -14,7 +15,13 @@ export function createRuntimeTransport(deps) {
14
15
  const phase = { "run.accepted": "accepted", "run.queued": "queued", "run.started": "running", "run.recovered": "running", "run.reconciling": "reconciling", "run.completed": "completed", "run.failed": "failed", "run.cancelled": "cancelled" }[event.eventType];
15
16
  return { ...event, payload: canonicalPayload(phase ? [{ kind: "run", phase }] : []) };
16
17
  };
17
- const serializeRun = (request, run) => deps.serializeRun?.(request, run) ?? run;
18
+ const serializeRun = (request, run) => {
19
+ const serialized = deps.serializeRun?.(request, run) ?? run;
20
+ // HTTP便于消费者关联原run;唯一持久来源仍为该run的原sessionOptions,绝不取当前会话。
21
+ const original = run.sessionOptions?.workContext;
22
+ const { workContext: _ignored, ...base } = serialized;
23
+ return validWorkContextIdentity(original) ? { ...base, workContext: workContextIdentity(original) } : base;
24
+ };
18
25
  const serializeDeviceRequest = (request, value) => deps.serializeDeviceRequest?.(request, value) ?? value;
19
26
  function json(res, status, body) {
20
27
  res.statusCode = status;
@@ -238,7 +245,7 @@ export function createRuntimeTransport(deps) {
238
245
  return json(res, 400, { error: "Missing deviceId or throughEventId" });
239
246
  }
240
247
  const store = deps.store();
241
- const requestedInstance = typeof body?.serverInstanceId === "string" ? body.serverInstanceId.trim() : "";
248
+ const requestedInstance = typeof body?.serverInstanceId === "string" ? body.serverInstanceId : "";
242
249
  if (requestedInstance && requestedInstance !== store.serverInstanceId) {
243
250
  return json(res, 409, {
244
251
  error: "serverInstanceId mismatch",
@@ -288,14 +295,15 @@ export function createRuntimeTransport(deps) {
288
295
  return json(res, 405, { error: "Method Not Allowed" });
289
296
  if (!authenticate(req, res))
290
297
  return true;
291
- const key = deps.resolveSessionKey?.(sessionKey.trim()) ?? sessionKey.trim();
292
- if (!key)
298
+ const key = deps.resolveSessionKey?.(sessionKey) ?? sessionKey;
299
+ if (!key.trim())
293
300
  return json(res, 400, { error: "Missing session key" });
294
- const nativeSnapshot = await deps.snapshot(key, integerQuery(new URL(req.url ?? "/", "http://localhost"), "transcriptLimit", 110), req);
301
+ const snapshotKey = req.headers["x-fridaynext-event-format"] === "canonical-v1" ? sessionKey : key;
302
+ const nativeSnapshot = await deps.snapshot(snapshotKey, integerQuery(new URL(req.url ?? "/", "http://localhost"), "transcriptLimit", 110), req);
295
303
  if (nativeSnapshot?.unavailable)
296
304
  return json(res, 503, { ok: false, code: "UNAVAILABLE", error: "Session changed while reading snapshot" });
297
305
  try {
298
- assertHistorySnapshotV1(nativeSnapshot, key);
306
+ assertHistorySnapshotV1(nativeSnapshot, snapshotKey);
299
307
  }
300
308
  catch (error) {
301
309
  if (error instanceof ChannelError && error.code === "HISTORY_CONTRACT_INVALID")
@@ -308,8 +316,7 @@ export function createRuntimeTransport(deps) {
308
316
  const url = new URL(req.url ?? "/", "http://localhost");
309
317
  const requestedRunIds = new Set(url.searchParams
310
318
  .getAll("runId")
311
- .map((runId) => runId.trim())
312
- .filter(Boolean));
319
+ .filter((runId) => runId.trim().length > 0));
313
320
  const segmentScope = url.searchParams.get("segments");
314
321
  const latestRunId = runs.at(-1)?.runId;
315
322
  const selectedRunIds = segmentScope === "none"
@@ -342,7 +349,7 @@ export function createRuntimeTransport(deps) {
342
349
  ok: true,
343
350
  protocolVersion: 3,
344
351
  serverInstanceId: store.serverInstanceId,
345
- sessionKey: nativeSnapshot.session?.sessionKey ?? key,
352
+ sessionKey: nativeSnapshot.session?.sessionKey ?? snapshotKey,
346
353
  ...(sessionId ? { sessionId } : {}),
347
354
  revision,
348
355
  runs: runs.map(run => serializeRun(req, run)),
@@ -357,6 +364,39 @@ export function createRuntimeTransport(deps) {
357
364
  ...(sessionUsage ? { sessionUsage } : {}),
358
365
  });
359
366
  }
367
+ async function handleQueuedMessageDelete(req, res, runId) {
368
+ if (req.method !== "DELETE")
369
+ return json(res, 405, { error: "Method Not Allowed" });
370
+ if (!authenticate(req, res))
371
+ return true;
372
+ res.setHeader("Cache-Control", "no-store");
373
+ const body = await readJsonBody(req);
374
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
375
+ return json(res, 400, { code: "QUEUED_DELETE_SCOPE_REQUIRED" });
376
+ }
377
+ const { deviceId, sessionKey, clientRequestId, expectedServerInstanceId } = body;
378
+ if (typeof deviceId !== "string" || !deviceId.trim() || typeof sessionKey !== "string" || !sessionKey
379
+ || typeof clientRequestId !== "string" || !clientRequestId || typeof expectedServerInstanceId !== "string"
380
+ || !expectedServerInstanceId || req.headers["x-fridaynext-device-id"] !== deviceId
381
+ || req.headers["x-fridaynext-server-instance-id"] !== expectedServerInstanceId) {
382
+ return json(res, 400, { code: "QUEUED_DELETE_SCOPE_REQUIRED" });
383
+ }
384
+ const store = deps.store();
385
+ if (expectedServerInstanceId !== store.serverInstanceId) {
386
+ return json(res, 409, { code: "SERVICE_IDENTITY_CHANGED", serverInstanceId: store.serverInstanceId });
387
+ }
388
+ const run = store.runForRequest(deviceId, clientRequestId);
389
+ if (!run || run.runId !== runId || run.parentRunId || run.origin === "observed"
390
+ || (run.sourceKind && run.sourceKind !== "session") || serializeRun(req, run).sessionKey !== sessionKey) {
391
+ return json(res, 404, { code: "QUEUED_MESSAGE_NOT_FOUND" });
392
+ }
393
+ if (store.queuedRunReserved(runId))
394
+ return json(res, 409, { code: "QUEUED_RUN_CONTROL_PENDING" });
395
+ const deleted = store.deleteQueuedMessage(runId);
396
+ if (!deleted)
397
+ return json(res, 409, { code: "QUEUED_MESSAGE_UNAVAILABLE" });
398
+ return json(res, 200, { ok: true, serverInstanceId: store.serverInstanceId, run: serializeRun(req, deleted) });
399
+ }
360
400
  async function handleRuntimeV3Cancel(req, res, runId) {
361
401
  if (req.method !== "DELETE")
362
402
  return json(res, 405, { error: "Method Not Allowed" });
@@ -373,6 +413,8 @@ export function createRuntimeTransport(deps) {
373
413
  return json(res, 200, { ok: true, runId, phase: run.phase, replayed: true });
374
414
  }
375
415
  if (run.phase === "queued") {
416
+ if (store.queuedRunReserved(runId))
417
+ return json(res, 409, { code: "QUEUED_RUN_CONTROL_PENDING" });
376
418
  deps.flush?.(runId);
377
419
  const event = store.appendRunEvent(runId, "run.cancelled", canonicalPayload([{ kind: "run", phase: "cancelled", data: { reason: "cancelled before dispatch" } }]));
378
420
  return json(res, 200, { ok: true, runId, phase: "cancelled", eventId: event.eventId });
@@ -396,5 +438,5 @@ export function createRuntimeTransport(deps) {
396
438
  ...result,
397
439
  });
398
440
  }
399
- return { handleRuntimeV3Events, handleRuntimeV3Acknowledge, handleRuntimeV3Sync, handleRuntimeV3SessionSnapshot, handleRuntimeV3Cancel };
441
+ return { handleRuntimeV3Events, handleRuntimeV3Acknowledge, handleRuntimeV3Sync, handleRuntimeV3SessionSnapshot, handleRuntimeV3Cancel, handleQueuedMessageDelete };
400
442
  }
@@ -1,17 +1,21 @@
1
- import { VERSIONED_SESSION_SETTINGS, VERSIONED_AGENT_DEFAULTS } from "../contract/types.js";
1
+ import { VERSIONED_SESSION_SETTINGS, VERSIONED_AGENT_DEFAULTS, SETTINGS_SCHEMA_V1 } from "../contract/types.js";
2
+ import { settingsSchemaFields, validDeclaredSettingsValues } from "../contract/settings-schema.js";
2
3
  import { readJsonBody } from "./body.js";
4
+ import { changesWorkContext, hasWorkContext } from "../runtime/work-context.js";
3
5
  const object = (value) => !!value && typeof value === "object" && !Array.isArray(value);
4
6
  function validSnapshot(value, identity, scopeKey) {
5
7
  return object(value) && value[scopeKey] === identity && typeof value.version === "string" && !!value.version.trim() && object(value.values);
6
8
  }
7
9
  function validMutation(value, scopeKey) {
8
- const fields = new Set(scopeKey === "agentId" ? ["modelRef", "thinkingLevel"] : ["modelRef", "thinkingLevel", "permissionMode", "cwd"]);
9
10
  return object(value) && ["commandId", "expectedVersion", "expectedServerInstanceId"].every(k => typeof value[k] === "string" && !!value[k].trim())
10
11
  && Object.keys(value).every(k => ["commandId", "expectedVersion", "expectedServerInstanceId", "values", ...(scopeKey === "sessionKey" ? ["sessionKey"] : [])].includes(k))
11
- && object(value.values) && Object.keys(value.values).length > 0
12
- && (scopeKey !== "agentId" || typeof value.values.modelRef === "string" && !!value.values.modelRef.trim()
13
- && (!Object.hasOwn(value.values, "thinkingLevel") || typeof value.values.thinkingLevel === "string" && !!value.values.thinkingLevel.trim()))
14
- && Object.entries(value.values).every(([key, v]) => fields.has(key) && (v === null || typeof v === "string"));
12
+ && object(value.values) && Object.keys(value.values).length > 0;
13
+ }
14
+ function validLegacyValues(change, defaults) {
15
+ const fields = new Set(defaults ? ["modelRef", "thinkingLevel"] : ["modelRef", "thinkingLevel", "permissionMode", "cwd"]);
16
+ return (!defaults || typeof change.values.modelRef === "string" && !!change.values.modelRef.trim()
17
+ && (!Object.hasOwn(change.values, "thinkingLevel") || typeof change.values.thinkingLevel === "string" && !!change.values.thinkingLevel.trim()))
18
+ && Object.entries(change.values).every(([key, value]) => fields.has(key) && (value === null || typeof value === "string"));
15
19
  }
16
20
  // 两种作用域共用原命令账本、并发串行化和未知结果对账。
17
21
  function createVersionedSettingsHandler(store, adapter, defaults) {
@@ -68,6 +72,7 @@ function createVersionedSettingsHandler(store, adapter, defaults) {
68
72
  if (req.method !== "PUT")
69
73
  return reply(405, { code: "METHOD_NOT_ALLOWED" });
70
74
  const body = await readJsonBody(req);
75
+ const declared = adapter.descriptor.capabilities.some(value => value.startsWith("settings.schema-"));
71
76
  if (!validMutation(body, scopeKey))
72
77
  return reply(400, { code: "INVALID_SETTINGS_MUTATION" });
73
78
  activeCommandId = body.commandId;
@@ -89,7 +94,34 @@ function createVersionedSettingsHandler(store, adapter, defaults) {
89
94
  return sendResult({ ...store.commandReceipt(KIND, body.commandId).response, replayed: true });
90
95
  if (status === "prepared")
91
96
  return await reconcile(body.commandId, payload);
97
+ if (!declared && !validLegacyValues(body, defaults))
98
+ return reply(400, { code: "INVALID_SETTINGS_MUTATION" });
99
+ // 原回执优先:当前字段或schema变化不能把已执行的命令重新解释为新写入。
100
+ let current;
101
+ if (declared) {
102
+ if (!adapter.descriptor.capabilities.includes(SETTINGS_SCHEMA_V1))
103
+ return reply(400, { code: "UNSUPPORTED_SETTINGS_SCHEMA" });
104
+ current = await read(identity);
105
+ if (!validSnapshot(current, identity, scopeKey))
106
+ throw new Error("invalid_settings_snapshot");
107
+ const fields = settingsSchemaFields(current);
108
+ if (!fields)
109
+ return reply(400, { code: "UNSUPPORTED_SETTINGS_SCHEMA" });
110
+ if (!validDeclaredSettingsValues(change.values, fields, defaults ? "agent" : "session"))
111
+ return reply(400, { code: "INVALID_SETTINGS_MUTATION" });
112
+ }
113
+ if (hasWorkContext(adapter) && changesWorkContext(change.values, current?.fields))
114
+ return reply(409, { code: "WORK_CONTEXT_MIGRATION_REQUIRED" });
92
115
  store.prepareCommandReceipt(KIND, body.commandId, payload, { [scopeKey]: identity, request: payload });
116
+ if (current && current.version !== change.expectedVersion) {
117
+ // current已按对应scopeKey验证,保留两种公开回执各自的snapshot类型。
118
+ const conflict = defaults
119
+ ? { status: "conflict", code: "SETTINGS_VERSION_CONFLICT", snapshot: current }
120
+ : { status: "conflict", code: "SETTINGS_VERSION_CONFLICT", snapshot: current };
121
+ const response = envelope(body.commandId, conflict);
122
+ store.completeCommandReceipt(KIND, body.commandId, payload, response);
123
+ return sendResult(response);
124
+ }
93
125
  try {
94
126
  const result = checked(await mutate(identity, change));
95
127
  const response = envelope(body.commandId, result);
@@ -46,8 +46,8 @@ export function createSessionHandlers(deps) {
46
46
  if (guard(req, res, ["GET"]))
47
47
  return true;
48
48
  const url = new URL(req.url ?? "/", "http://localhost");
49
- const key = url.searchParams.get("sessionKey")?.trim(), id = url.searchParams.get("id")?.trim();
50
- if (!key || !id)
49
+ const key = url.searchParams.get("sessionKey"), id = url.searchParams.get("id");
50
+ if (!key?.trim() || !id?.trim())
51
51
  return json(res, 400, {
52
52
  error: "Missing required query params: sessionKey, id",
53
53
  });
@@ -65,8 +65,8 @@ export function createSessionHandlers(deps) {
65
65
  async handleSessionTitle(req, res) {
66
66
  if (guard(req, res, ["PUT", "POST"]))
67
67
  return true;
68
- const body = await readJsonBody(req), key = typeof body?.sessionKey === "string" ? body.sessionKey.trim() : "";
69
- if (!key)
68
+ const body = await readJsonBody(req), key = typeof body?.sessionKey === "string" ? body.sessionKey : "";
69
+ if (!key.trim())
70
70
  return json(res, 400, { error: "Missing required field: sessionKey" });
71
71
  if (body?.title !== undefined && typeof body.title !== "string")
72
72
  return json(res, 400, { error: "Field title must be a string" });
@@ -81,8 +81,8 @@ export function createSessionHandlers(deps) {
81
81
  async handleSessionPin(req, res) {
82
82
  if (guard(req, res, ["PUT"]))
83
83
  return true;
84
- const body = await readJsonBody(req), key = typeof body?.sessionKey === "string" ? body.sessionKey.trim() : "";
85
- if (!key)
84
+ const body = await readJsonBody(req), key = typeof body?.sessionKey === "string" ? body.sessionKey : "";
85
+ if (!key.trim())
86
86
  return json(res, 400, { error: "Missing required field: sessionKey" });
87
87
  if (typeof body?.pinned !== "boolean")
88
88
  return json(res, 400, { error: "Field pinned must be a boolean" });
@@ -97,13 +97,13 @@ export function createSessionHandlers(deps) {
97
97
  async handleSessionBind(req, res) {
98
98
  if (guard(req, res, ["POST"]))
99
99
  return true;
100
- const body = await readJsonBody(req), key = typeof body?.sessionKey === "string" ? body.sessionKey.trim() : "";
100
+ const body = await readJsonBody(req), key = typeof body?.sessionKey === "string" ? body.sessionKey : "";
101
101
  const deviceId = typeof body?.deviceId === "string"
102
102
  ? body.deviceId.trim().toUpperCase()
103
103
  : "";
104
104
  if (!deviceId)
105
105
  return json(res, 400, { error: "Missing required field: deviceId" });
106
- if (!key)
106
+ if (!key.trim())
107
107
  return json(res, 400, { error: "Missing required field: sessionKey" });
108
108
  if (!deps.bind)
109
109
  return unsupported(res);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syengup/fridaynext-channel-kit",
3
- "version": "0.1.4-beta.6",
3
+ "version": "0.2.0-beta.9",
4
4
  "description": "FridayNext 的框架无关客户端契约与持久运行设施",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,11 +22,6 @@
22
22
  "./*": "./dist/*.js",
23
23
  "./runtime/channel-kernel": null
24
24
  },
25
- "scripts": {
26
- "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.json",
27
- "test": "pnpm build && node --test tests/*.test.mjs",
28
- "prepack": "pnpm build"
29
- },
30
25
  "devDependencies": {
31
26
  "@types/node": "25.6.0",
32
27
  "jsqr": "1.4.0",
@@ -36,5 +31,9 @@
36
31
  },
37
32
  "dependencies": {
38
33
  "node-app-attest": "1.0.1"
34
+ },
35
+ "scripts": {
36
+ "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.json",
37
+ "test": "pnpm build && node --test tests/*.test.mjs"
39
38
  }
40
- }
39
+ }
@@ -138,14 +138,9 @@ For JSPM users:
138
138
 
139
139
  ## Deployment
140
140
 
141
- - Choose your new version number
142
- - Set it in `package.json` and `bower.json`
143
- - Create a tag: `git tag [version]`
144
- - Push the tag: `git push --tags`
145
- - Create a [release in GitHub](https://github.com/microsoft/tslib/releases)
146
- - Run the [publish to npm](https://github.com/microsoft/tslib/actions?query=workflow%3A%22Publish+to+NPM%22) workflow
147
-
148
- Done.
141
+ - Run the **Bump tslib** GitHub workflow and choose patch, minor, or major
142
+ - Review and squash-merge the generated version-bump PR
143
+ - The release runs automatically: tag, build, publish to npm, and create a GitHub release with generated notes
149
144
 
150
145
  # Contribute
151
146
 
@@ -2,7 +2,7 @@
2
2
  "name": "tslib",
3
3
  "author": "Microsoft Corp.",
4
4
  "homepage": "https://www.typescriptlang.org/",
5
- "version": "2.8.1",
5
+ "version": "2.9.1",
6
6
  "license": "0BSD",
7
7
  "description": "Runtime library for TypeScript helper functions",
8
8
  "keywords": [