@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
@@ -1,6 +1,10 @@
1
1
  import { canonicalPayload, } from "../contract/types.js";
2
2
  import { reconcileRun, waitForDispatchSlot } from "./scheduler.js";
3
3
  import { DeviceRequestCoordinator } from "../device-request/coordinator.js";
4
+ import { assertWorkContextAdmission, assertWorkContextLocks, changesWorkContext, hasWorkContext } from "./work-context.js";
5
+ import { sameWorkContext, validWorkContextIdentity } from "../contract/work-context.js";
6
+ import { ChannelError } from "../contract/types.js";
7
+ import { CanonicalUpdateBatcher } from "./canonical-update-batcher.js";
4
8
  const terminal = (phase) => ["completed", "failed", "cancelled"].includes(phase);
5
9
  // 唯一执行编排:适配器提供宿主事实和执行租约,不领取队列、不结算通用状态。
6
10
  export class ChannelRunner {
@@ -9,6 +13,7 @@ export class ChannelRunner {
9
13
  reportError;
10
14
  recoveryOptions;
11
15
  devices;
16
+ streamBatches;
12
17
  jobs = new Map();
13
18
  restoring;
14
19
  stopped = false;
@@ -19,10 +24,38 @@ export class ChannelRunner {
19
24
  this.reportError = reportError;
20
25
  this.recoveryOptions = recoveryOptions;
21
26
  this.devices = new DeviceRequestCoordinator(store);
27
+ this.streamBatches = new CanonicalUpdateBatcher(entries => {
28
+ const first = entries[0];
29
+ const payload = canonicalPayload(entries.flatMap(entry => entry.updates));
30
+ const event = store.appendRunEvent(first.key, first.eventType, payload);
31
+ if (event.eventType !== first.eventType.trim() || JSON.stringify(event.payload) !== JSON.stringify(payload))
32
+ throw new Error("BUFFERED_DELIVERY_NOT_COMMITTED");
33
+ this.cleanupTerminal(first.key);
34
+ return event;
35
+ });
22
36
  }
23
37
  async admit(input) {
38
+ const original = structuredClone(input);
39
+ const replay = this.store.lookupCommand(original);
40
+ if (replay) {
41
+ await this.adapter.validateCommandReplay?.(original);
42
+ if (replay.run && replay.outcome === "replayed")
43
+ this.adapter.attachRun?.(replay.run);
44
+ return replay;
45
+ }
46
+ await assertWorkContextAdmission(this.adapter, this.store, input.sessionKey, input.sessionOptions?.workContext);
47
+ if (hasWorkContext(this.adapter) && changesWorkContext(input.sessionOptions ?? {}, undefined, true))
48
+ throw new ChannelError(409, "WORK_CONTEXT_MIGRATION_REQUIRED", "发送选项不能改变工作目录");
24
49
  const command = (await this.adapter.resolveCommand?.(input)) ?? input;
25
- const result = this.store.acceptCommand(command);
50
+ const expected = original.sessionOptions?.workContext, resolved = command.sessionOptions?.workContext;
51
+ if ((expected !== undefined || resolved !== undefined) && (!validWorkContextIdentity(expected) || !validWorkContextIdentity(resolved) || !sameWorkContext(expected, resolved)))
52
+ throw new ChannelError(409, "WORK_CONTEXT_CONFLICT", "解析不能改写原工作上下文");
53
+ if (validWorkContextIdentity(expected)) {
54
+ const current = await assertWorkContextAdmission(this.adapter, this.store, command.sessionKey, expected);
55
+ if (current)
56
+ assertWorkContextLocks(this.store, command.sessionKey, current);
57
+ }
58
+ const result = this.store.acceptCommand(command, original);
26
59
  if (result.run && result.outcome !== "conflict") {
27
60
  this.store.remapSessionSubscriptions(input.sessionKey, command.sessionKey);
28
61
  result.run = this.store.run(result.run.runId);
@@ -92,6 +125,8 @@ export class ChannelRunner {
92
125
  const current = this.store.run(runId);
93
126
  if (!current || terminal(current.phase))
94
127
  return;
128
+ this.adapter.flushRun?.(runId);
129
+ this.streamBatches.flush(runId);
95
130
  this.store.appendRunEvent(runId, `run.${result.state}`, canonicalPayload([
96
131
  {
97
132
  kind: "run",
@@ -113,6 +148,7 @@ export class ChannelRunner {
113
148
  if (!current || terminal(current.phase))
114
149
  return;
115
150
  this.adapter.flushRun?.(run.runId);
151
+ this.streamBatches.flush(run.runId);
116
152
  this.store.appendRunEvent(run.runId, "run.failed", canonicalPayload([
117
153
  {
118
154
  kind: "run",
@@ -132,14 +168,22 @@ export class ChannelRunner {
132
168
  this.store.appendRunEvent(run.runId, "dispatch.started", canonicalPayload([{ kind: "run", phase: "dispatching" }]));
133
169
  const result = await this.adapter.execute(run, {
134
170
  emit: (type, updates) => {
171
+ this.streamBatches.flush(run.runId);
135
172
  const event = this.store.appendRunEvent(run.runId, type, canonicalPayload(updates));
136
173
  this.cleanupTerminal(run.runId);
137
174
  return event;
138
175
  },
176
+ emitBuffered: (type, updates) => {
177
+ void this.streamBatches.enqueue(run.runId, type, updates, undefined).catch(this.reportError);
178
+ },
139
179
  isCancelled: () => ["cancelPending", "cancelled"].includes(this.store.run(run.runId)?.phase ?? "cancelled"),
140
- requestDevice: (input) => this.devices.request(run, input),
180
+ requestDevice: (input) => {
181
+ this.streamBatches.flush(run.runId);
182
+ return this.devices.request(run, input);
183
+ },
141
184
  });
142
185
  this.adapter.flushRun?.(run.runId);
186
+ this.streamBatches.flush(run.runId);
143
187
  const current = this.store.run(run.runId);
144
188
  if (current && !terminal(current.phase)) {
145
189
  if (result && !terminal(result.state)) {
@@ -258,6 +302,12 @@ export class ChannelRunner {
258
302
  }
259
303
  // 停服务只停止尚未领取的本地调度;远端任务继续,重启后以原身份对账。
260
304
  stop() {
305
+ try {
306
+ this.streamBatches.close();
307
+ }
308
+ catch (error) {
309
+ this.reportError(error);
310
+ }
261
311
  this.stopped = true;
262
312
  for (const recovery of this.recoveries.values())
263
313
  recovery.stop.abort();
@@ -0,0 +1,13 @@
1
+ import { type BackendAdapter } from "../contract/types.js";
2
+ import { type WorkContextIdentity, type WorkContextSnapshot } from "../contract/work-context.js";
3
+ import type { DurableRunStore } from "./durable-run-store.js";
4
+ export declare const hasWorkContext: (adapter: BackendAdapter) => boolean;
5
+ export declare function workContextCapabilityAllowed(adapter: BackendAdapter, sessionKey: string): boolean;
6
+ export declare function readWorkContext(adapter: BackendAdapter, store: DurableRunStore, sessionKey: string): Promise<WorkContextSnapshot>;
7
+ export declare function pendingWorkspaceCommand(store: DurableRunStore, target: WorkContextIdentity, exceptKey?: string): boolean;
8
+ export declare function assertWorkContextAdmission(adapter: BackendAdapter, store: DurableRunStore, sessionKey: string, expected: unknown): Promise<WorkContextSnapshot | undefined>;
9
+ export declare function assertWorkContextLocks(store: DurableRunStore, sessionKey: string, current: WorkContextSnapshot): void;
10
+ export declare function changesWorkContext(values: Record<string, unknown>, fields?: {
11
+ id: string;
12
+ effect?: string;
13
+ }[], allowIdentity?: boolean): boolean;
@@ -0,0 +1,73 @@
1
+ import { ChannelError } from "../contract/types.js";
2
+ import { WORK_CONTEXT_V1, sameWorkContext, sameWorkspace, validWorkContextIdentity, validWorkContextSnapshot, workContextCanSend, workContextObject } from "../contract/work-context.js";
3
+ export const hasWorkContext = (adapter) => adapter.descriptor.capabilities.some(value => value.startsWith("sessions.work-context-"));
4
+ export function workContextCapabilityAllowed(adapter, sessionKey) {
5
+ if (!adapter.descriptor.capabilities.includes(WORK_CONTEXT_V1) || !adapter.readWorkContext)
6
+ return false;
7
+ const details = adapter.descriptor.capabilityDetails;
8
+ if (!details)
9
+ return true;
10
+ if (details.version !== 1 || !workContextObject(details.capabilities))
11
+ return false;
12
+ const constraint = details.capabilities[WORK_CONTEXT_V1];
13
+ if (constraint === undefined)
14
+ return true;
15
+ return workContextObject(constraint) && (constraint.permission === undefined || constraint.permission === "allowed")
16
+ && (constraint.scope === undefined || constraint.scope === "service" || constraint.scope === "session")
17
+ && (constraint.scope !== "session" || constraint.sessionKey === sessionKey)
18
+ && (constraint.sessionKey === undefined || constraint.sessionKey === sessionKey);
19
+ }
20
+ export async function readWorkContext(adapter, store, sessionKey) {
21
+ if (!adapter.descriptor.capabilities.includes(WORK_CONTEXT_V1) || !adapter.readWorkContext)
22
+ throw new ChannelError(404, "UNSUPPORTED_WORK_CONTEXT", "工作上下文能力不可读");
23
+ let current;
24
+ try {
25
+ current = await adapter.readWorkContext(sessionKey);
26
+ }
27
+ catch {
28
+ throw new ChannelError(503, "WORK_CONTEXT_UNAVAILABLE", "工作上下文不可验证");
29
+ }
30
+ if (!validWorkContextSnapshot(current))
31
+ throw new ChannelError(503, "WORK_CONTEXT_UNAVAILABLE", "工作上下文快照无效");
32
+ if (current.serverInstanceId !== store.serverInstanceId)
33
+ throw new ChannelError(409, "WORK_CONTEXT_CONFLICT", "工作上下文服务不匹配");
34
+ return current;
35
+ }
36
+ export function pendingWorkspaceCommand(store, target, exceptKey) {
37
+ return store.pendingCommandReceipts("backend-operation-v1").some(receipt => {
38
+ if (receipt.commandId === exceptKey)
39
+ return false;
40
+ const request = receipt.context?.request;
41
+ if (!workContextObject(request) || typeof request.operationId !== "string" || !request.operationId.startsWith("workspace."))
42
+ return false;
43
+ const input = workContextObject(request.input) ? request.input : {};
44
+ return [request.workContext, input.target].some(value => validWorkContextIdentity(value) && sameWorkspace(value, target));
45
+ });
46
+ }
47
+ export async function assertWorkContextAdmission(adapter, store, sessionKey, expected) {
48
+ if (expected === undefined && !hasWorkContext(adapter))
49
+ return;
50
+ if (!adapter.descriptor.capabilities.includes(WORK_CONTEXT_V1))
51
+ throw new ChannelError(404, "UNSUPPORTED_WORK_CONTEXT", "未声明工作上下文合同");
52
+ if (!validWorkContextIdentity(expected))
53
+ throw new ChannelError(400, "INVALID_WORK_CONTEXT", "缺少原工作上下文身份");
54
+ if (!workContextCapabilityAllowed(adapter, sessionKey))
55
+ throw new ChannelError(409, "WORK_CONTEXT_NOT_WRITABLE", "工作上下文能力作用域不允许写入");
56
+ const current = await readWorkContext(adapter, store, sessionKey);
57
+ if (!sameWorkContext(expected, current))
58
+ throw new ChannelError(409, "WORK_CONTEXT_CONFLICT", "工作上下文版本或作用域已变化");
59
+ if (!workContextCanSend(current))
60
+ throw new ChannelError(409, "WORK_CONTEXT_NOT_WRITABLE", "工作上下文尚不可发送");
61
+ assertWorkContextLocks(store, sessionKey, current);
62
+ return current;
63
+ }
64
+ export function assertWorkContextLocks(store, sessionKey, current) {
65
+ if (pendingWorkspaceCommand(store, current))
66
+ throw new ChannelError(409, "WORK_CONTEXT_NOT_WRITABLE", "工作上下文事务仍待对账");
67
+ if (current.state === "draft" && store.runs().some(run => run.sessionKey === sessionKey && !["completed", "failed", "cancelled"].includes(run.phase)))
68
+ throw new ChannelError(409, "WORK_CONTEXT_BUSY", "草稿首次绑定仍在对账");
69
+ }
70
+ // 原生管理端口必须明确保证不变更绑定;公共层不检查宿主配置键或路径。
71
+ export function changesWorkContext(values, fields, allowIdentity = false) {
72
+ return Object.keys(values).some(key => key === "cwd" || key === "workContext" && !allowIdentity || fields?.some(field => field.id === key && field.effect === "working-directory"));
73
+ }
@@ -146,7 +146,7 @@ export class ChannelService extends ChannelKernel {
146
146
  const cors = this.serviceOptions.cors?.();
147
147
  if (cors?.enabled) {
148
148
  res.setHeader("Access-Control-Allow-Origin", cors.allowOrigin || "*");
149
- res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Last-Event-ID, X-FridayNext-Event-Format, X-FridayNext-Server-Instance-ID, X-FridayNext-Attest");
149
+ res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Last-Event-ID, X-FridayNext-Event-Format, X-FridayNext-Server-Instance-ID, X-FridayNext-Device-ID, X-FridayNext-Attest");
150
150
  res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS");
151
151
  }
152
152
  if (req.method === "OPTIONS") {
@@ -0,0 +1,47 @@
1
+ import type { DurableCommandReceipt, DurableRunStore } from "../runtime/durable-run-store.js";
2
+ export declare const commandLifecycleCapability = "commands.lifecycle-v2";
3
+ export type LifecycleCommandScope = {
4
+ expectedServerInstanceId: string;
5
+ deviceId: string;
6
+ agentId: string;
7
+ sessionKey?: string;
8
+ commandId: string;
9
+ };
10
+ export type LifecycleCommandRequest = LifecycleCommandScope & {
11
+ version: 1;
12
+ input: Record<string, unknown>;
13
+ };
14
+ type TerminalStatus = "completed" | "failed" | "skipped";
15
+ type Response = Record<string, unknown>;
16
+ export type CommandLifecycleReceipt = {
17
+ status: "accepted" | "running" | "reconciling" | TerminalStatus | "conflict";
18
+ code?: string;
19
+ response?: Response;
20
+ };
21
+ type Options = {
22
+ store: DurableRunStore;
23
+ kind: string;
24
+ handles(request: LifecycleCommandRequest): boolean;
25
+ reserveQueuedRun?(request: LifecycleCommandRequest): {
26
+ runId: string;
27
+ } | {
28
+ code: string;
29
+ };
30
+ hasDispatched(row: DurableCommandReceipt): boolean;
31
+ outcome(response: Response): TerminalStatus;
32
+ execute(request: LifecycleCommandRequest): Promise<Response | undefined> | Response | undefined;
33
+ inspect(request: LifecycleCommandRequest): Promise<Response | undefined> | Response | undefined;
34
+ };
35
+ export declare function createCommandLifecycle({ store, kind, handles, reserveQueuedRun, hasDispatched, outcome, execute, inspect }: Options): {
36
+ serverInstanceId: string;
37
+ handles: (request: LifecycleCommandRequest) => boolean;
38
+ blocks: (scope: Pick<LifecycleCommandScope, "sessionKey">, exceptKey?: string) => boolean;
39
+ submit(request: LifecycleCommandRequest): CommandLifecycleReceipt;
40
+ lookup(scope: LifecycleCommandScope): CommandLifecycleReceipt | undefined;
41
+ wait(scope: LifecycleCommandScope): Promise<void> | undefined;
42
+ start(): void;
43
+ close(): void;
44
+ };
45
+ export declare const commandLifecycleExecutePath = "/friday-next/commands/v2/execute";
46
+ export declare function createCommandLifecycleRoute(lifecycle: Pick<ReturnType<typeof createCommandLifecycle>, "serverInstanceId" | "submit" | "lookup">, authenticate: (request: import("node:http").IncomingMessage) => boolean): (req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => Promise<boolean>;
47
+ export {};
@@ -0,0 +1,184 @@
1
+ export const commandLifecycleCapability = "commands.lifecycle-v2";
2
+ const keyOf = ({ deviceId, commandId }) => JSON.stringify([deviceId, commandId]);
3
+ const requestOf = (row) => row.context?.request;
4
+ export function createCommandLifecycle({ store, kind, handles, reserveQueuedRun, hasDispatched, outcome, execute, inspect }) {
5
+ const workers = new Map();
6
+ const executing = new Set();
7
+ let timer;
8
+ let closed = false;
9
+ function project(row) {
10
+ if (row.state === "succeeded")
11
+ return { status: outcome(row.response), response: row.response };
12
+ if (hasDispatched(row))
13
+ return { status: executing.has(row.commandId) ? "running" : "reconciling" };
14
+ return { status: row.context?.lifecycle === 2 && !row.context.progress ? "accepted" : "reconciling" };
15
+ }
16
+ function schedule(row, request) {
17
+ const key = row.commandId;
18
+ if (closed || row.state !== "prepared" || workers.has(key))
19
+ return;
20
+ const start = row.context?.lifecycle === 2 && !row.context.progress && !hasDispatched(row);
21
+ // 在调用宿主前记下接管意图。宿主必须在实际写入前再保存自己的派发证据。
22
+ const task = new Promise(resolve => setImmediate(resolve)).then(async () => {
23
+ if (closed || store.commandReceipt(kind, key) !== row)
24
+ return;
25
+ if (start) {
26
+ store.checkpointCommandReceipt(kind, key, request, { lifecycleDispatchAttempted: true });
27
+ executing.add(key);
28
+ }
29
+ const response = await (start ? execute(request) : inspect(request));
30
+ if (response && !closed && store.commandReceipt(kind, key)?.state === "prepared") {
31
+ store.completeCommandReceipt(kind, key, request, response);
32
+ }
33
+ }).catch(() => {
34
+ // 传输异常保持原编号。下一轮只读取宿主证据。
35
+ }).finally(() => {
36
+ executing.delete(key);
37
+ workers.delete(key);
38
+ });
39
+ workers.set(key, task);
40
+ }
41
+ function reconcile() {
42
+ for (const row of store.pendingCommandReceipts(kind)) {
43
+ const request = requestOf(row);
44
+ if (request && handles(request))
45
+ schedule(row, request);
46
+ }
47
+ }
48
+ function blocks(scope, exceptKey) {
49
+ return store.pendingCommandReceipts(kind).some(row => {
50
+ const request = requestOf(row);
51
+ return row.commandId !== exceptKey && request && handles(request) && request.sessionKey === scope.sessionKey;
52
+ });
53
+ }
54
+ return {
55
+ serverInstanceId: store.serverInstanceId,
56
+ handles,
57
+ blocks,
58
+ submit(request) {
59
+ if (request.expectedServerInstanceId !== store.serverInstanceId || !handles(request)) {
60
+ return { status: "conflict", code: "INVALID_COMMAND_SCOPE" };
61
+ }
62
+ const key = keyOf(request);
63
+ const existing = store.commandReceiptStatus(kind, key, request);
64
+ if (existing === "conflict")
65
+ return { status: "conflict", code: "COMMAND_ID_CONFLICT" };
66
+ if (existing === "missing" && blocks(request, key))
67
+ return { status: "conflict", code: "COMMAND_SESSION_BUSY" };
68
+ let reservedQueuedRunId;
69
+ if (existing === "missing" && reserveQueuedRun) {
70
+ const reservation = reserveQueuedRun(request);
71
+ if ("code" in reservation)
72
+ return { status: "conflict", code: reservation.code };
73
+ const run = store.run(reservation.runId);
74
+ if (!run || run.identityVersion !== 2 || run.origin !== "command" || run.phase !== "queued" ||
75
+ run.deviceId !== request.deviceId.trim().toUpperCase() || run.agentId !== request.agentId ||
76
+ run.sessionKey !== request.sessionKey || store.queuedRunReserved(run.runId)) {
77
+ return { status: "conflict", code: "QUEUED_RUN_UNAVAILABLE" };
78
+ }
79
+ reservedQueuedRunId = run.runId;
80
+ }
81
+ const row = existing === "missing"
82
+ ? store.prepareCommandReceipt(kind, key, request, { request, lifecycle: 2,
83
+ ...(reservedQueuedRunId ? { reservedQueuedRunId } : {}) })
84
+ : store.commandReceipt(kind, key);
85
+ schedule(row, request);
86
+ return project(row);
87
+ },
88
+ lookup(scope) {
89
+ const row = store.commandReceipt(kind, keyOf(scope));
90
+ const request = row && requestOf(row);
91
+ if (!row || !request || !handles(request) || scope.expectedServerInstanceId !== store.serverInstanceId ||
92
+ request.expectedServerInstanceId !== scope.expectedServerInstanceId || request.agentId !== scope.agentId ||
93
+ request.sessionKey !== scope.sessionKey || request.deviceId !== scope.deviceId || request.commandId !== scope.commandId)
94
+ return;
95
+ return project(row);
96
+ },
97
+ wait(scope) {
98
+ return workers.get(keyOf(scope));
99
+ },
100
+ start() {
101
+ if (closed || timer)
102
+ return;
103
+ reconcile();
104
+ timer = setInterval(reconcile, 2_000);
105
+ timer.unref();
106
+ },
107
+ close() {
108
+ closed = true;
109
+ clearInterval(timer);
110
+ },
111
+ };
112
+ }
113
+ export const commandLifecycleExecutePath = "/friday-next/commands/v2/execute";
114
+ const receiptPrefix = "/friday-next/commands/v2/receipts/";
115
+ const isIdentity = (value) => typeof value === "string" && !!value.trim() && value.length <= 1024;
116
+ const isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
117
+ export function createCommandLifecycleRoute(lifecycle, authenticate) {
118
+ return async (req, res) => {
119
+ const url = new URL(req.url ?? "/", "https://localhost");
120
+ const execute = url.pathname === commandLifecycleExecutePath;
121
+ if (!execute && !url.pathname.startsWith(receiptPrefix))
122
+ return false;
123
+ const reply = (status, value) => {
124
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
125
+ res.end(JSON.stringify(value));
126
+ return true;
127
+ };
128
+ if (!authenticate(req))
129
+ return reply(401, { code: "UNAUTHORIZED" });
130
+ if (req.method !== (execute ? "POST" : "GET"))
131
+ return reply(405, { code: "METHOD_NOT_ALLOWED" });
132
+ const service = req.headers["x-fridaynext-server-instance-id"];
133
+ const device = req.headers["x-fridaynext-device-id"];
134
+ if (!isIdentity(service) || !isIdentity(device))
135
+ return reply(400, { code: "INVALID_COMMAND_SCOPE" });
136
+ if (service !== lifecycle.serverInstanceId)
137
+ return reply(409, { code: "SERVICE_IDENTITY_CHANGED" });
138
+ const envelope = (scope, receipt) => ({
139
+ version: 2, serverInstanceId: service, deviceId: device, agentId: scope.agentId,
140
+ sessionKey: scope.sessionKey, commandId: scope.commandId, ...receipt,
141
+ });
142
+ if (execute) {
143
+ let body;
144
+ try {
145
+ const chunks = [];
146
+ let size = 0;
147
+ for await (const chunk of req) {
148
+ size += chunk.length;
149
+ if (size > 128 * 1024)
150
+ throw new Error();
151
+ chunks.push(chunk);
152
+ }
153
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
154
+ }
155
+ catch {
156
+ return reply(400, { code: "INVALID_COMMAND_INPUT" });
157
+ }
158
+ if (!isObject(body) || Object.keys(body).some(key => !["version", "expectedServerInstanceId", "deviceId", "agentId", "sessionKey", "commandId", "input"].includes(key)) ||
159
+ body.version !== 1 || body.expectedServerInstanceId !== service || body.deviceId !== device ||
160
+ !isIdentity(body.agentId) || !isIdentity(body.sessionKey) || !isIdentity(body.commandId) || !isObject(body.input)) {
161
+ return reply(400, { code: "INVALID_COMMAND_INPUT" });
162
+ }
163
+ const scope = body;
164
+ const receipt = lifecycle.submit(scope);
165
+ const status = receipt.status === "conflict" ? 409 : receipt.response ? 200 : 202;
166
+ return reply(status, envelope(scope, receipt));
167
+ }
168
+ let commandId;
169
+ try {
170
+ commandId = decodeURIComponent(url.pathname.slice(receiptPrefix.length));
171
+ }
172
+ catch {
173
+ return reply(400, { code: "INVALID_COMMAND_SCOPE" });
174
+ }
175
+ const agentId = url.searchParams.get("agentId");
176
+ const sessionKey = url.searchParams.get("sessionKey");
177
+ if (!isIdentity(agentId) || !isIdentity(sessionKey) || !isIdentity(commandId) || commandId.includes("/")) {
178
+ return reply(400, { code: "INVALID_COMMAND_SCOPE" });
179
+ }
180
+ const scope = { expectedServerInstanceId: service, deviceId: device, agentId, sessionKey, commandId };
181
+ const receipt = lifecycle.lookup(scope);
182
+ return reply(receipt ? 200 : 404, envelope(scope, receipt ?? { status: "missing" }));
183
+ };
184
+ }
@@ -3,7 +3,7 @@ import type { BackendAdapter } from "../contract/types.js";
3
3
  import type { DurableRunStore } from "../runtime/durable-run-store.js";
4
4
  export interface ControlHandlerEnvironment {
5
5
  store(): DurableRunStore;
6
- adapter: Pick<BackendAdapter, "lookupControl" | "respondControl">;
6
+ adapter: Pick<BackendAdapter, "lookupControl" | "respondControl"> & Partial<Pick<BackendAdapter, "descriptor">>;
7
7
  authenticate(req: IncomingMessage): boolean;
8
8
  }
9
9
  export declare function createControlHandler(deps: ControlHandlerEnvironment): (req: IncomingMessage, res: ServerResponse, id: string, responseRoute: boolean) => Promise<boolean>;
@@ -1,4 +1,5 @@
1
1
  import { readJsonBody } from "./body.js";
2
+ import { WORK_CONTEXT_V1, sameWorkContext, validWorkContextIdentity } from "../contract/work-context.js";
2
3
  export function createControlHandler(deps) {
3
4
  const submissions = new Map();
4
5
  async function handleControl(req, res, id, responseRoute) {
@@ -39,6 +40,7 @@ export function createControlHandler(deps) {
39
40
  requestId: id,
40
41
  generation: body.generation,
41
42
  answer: body.answer,
43
+ ...(body.workContext !== undefined ? { workContext: body.workContext } : {}),
42
44
  };
43
45
  const store = deps.store();
44
46
  let status = store.commandReceiptStatus("control", body.commandId, payload);
@@ -50,6 +52,15 @@ export function createControlHandler(deps) {
50
52
  replayed: true,
51
53
  });
52
54
  const current = await adapter.lookupControl(id);
55
+ if (adapter.descriptor?.capabilities.includes(WORK_CONTEXT_V1) && current) {
56
+ const run = store.run(current.runId), original = run?.origin === "observed"
57
+ ? run.observedWorkContext : run?.sessionOptions?.workContext;
58
+ if (!run || run.sessionKey !== current.sessionKey || !validWorkContextIdentity(original) ||
59
+ original.serverInstanceId !== store.serverInstanceId)
60
+ return reply(409, { code: "CONTROL_CONTEXT_UNAVAILABLE" });
61
+ if (body.workContext !== undefined && (!validWorkContextIdentity(body.workContext) || !sameWorkContext(body.workContext, original)))
62
+ return reply(409, { code: "CONTROL_CONTEXT_MISMATCH" });
63
+ }
53
64
  // 权威查询会让出执行;另一个请求可能已用相同命令身份准备了不同操作。
54
65
  status = store.commandReceiptStatus("control", body.commandId, payload);
55
66
  if (status === "conflict")
@@ -1,4 +1,4 @@
1
- import { canonicalPayload } from "../contract/types.js";
1
+ import { canonicalPayload, ChannelError } from "../contract/types.js";
2
2
  import { readJsonBody } from "./body.js";
3
3
  // 所有新后端和规范化宿主入口共用这一生产准入路径;适配器只处理宿主映射及执行。
4
4
  export function createMessageHandler(deps) {
@@ -63,11 +63,17 @@ export function createMessageHandler(deps) {
63
63
  attachments,
64
64
  sessionOptions,
65
65
  };
66
- if (deps.resolve)
67
- command = await deps.resolve(command);
68
- const accepted = deps.admit
69
- ? await deps.admit(command)
70
- : store.acceptCommand(command);
66
+ let accepted;
67
+ try {
68
+ if (deps.resolve)
69
+ command = await deps.resolve(command);
70
+ accepted = deps.admit ? await deps.admit(command) : store.acceptCommand(command);
71
+ }
72
+ catch (error) {
73
+ if (error instanceof ChannelError)
74
+ return reply(error.status, { code: error.code });
75
+ throw error;
76
+ }
71
77
  if (!accepted.run ||
72
78
  accepted.outcome === "conflict" ||
73
79
  accepted.outcome === "deleted")
@@ -0,0 +1,13 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { type BackendAdapter } from "../contract/types.js";
3
+ import { type OperationId } from "../contract/operations.js";
4
+ import type { DurableRunStore } from "../runtime/durable-run-store.js";
5
+ export interface OperationTransportPolicy {
6
+ /** 在Bearer/Attest门禁之后解析请求设备上下文;body不能覆盖此身份。 */
7
+ operationIdentity?(req: IncomingMessage): {
8
+ deviceId: string;
9
+ } | undefined;
10
+ /** SDK原有的细粒度鉴权由适配层接入,不把宿主角色写进公共合同。 */
11
+ authorizeOperation?(req: IncomingMessage, id: OperationId): boolean | Promise<boolean>;
12
+ }
13
+ export declare function createOperationHandler(store: DurableRunStore, adapter: BackendAdapter, policy: OperationTransportPolicy): (req: IncomingMessage, res: ServerResponse) => Promise<boolean>;