omp-superagent 0.1.13 → 0.1.16

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 (78) hide show
  1. package/DESIGN.md +8 -5
  2. package/THIRD_PARTY_NOTICES.md +6 -0
  3. package/assets/architecture-dark.svg +4 -4
  4. package/assets/architecture.ko-dark.svg +4 -4
  5. package/assets/architecture.ko.svg +4 -4
  6. package/assets/architecture.mmd +5 -5
  7. package/assets/architecture.svg +4 -4
  8. package/config.example.json +1 -0
  9. package/docs/OPERATIONS.en.md +80 -23
  10. package/docs/OPERATIONS.md +73 -18
  11. package/docs/design/execution.md +180 -43
  12. package/docs/design/messaging.md +62 -10
  13. package/docs/releases/0.1.15.md +13 -0
  14. package/docs/releases/0.1.16.md +9 -0
  15. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  16. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  17. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  18. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  19. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  20. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  21. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  22. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  23. package/package.json +6 -3
  24. package/scripts/prepare-worker-memory.ts +37 -0
  25. package/skills/head/SKILL.md +29 -47
  26. package/skills/head/references/routing.md +35 -16
  27. package/skills/head/references/supervision.md +10 -14
  28. package/skills/lane/SKILL.md +14 -16
  29. package/skills/lane/references/workflow.md +14 -27
  30. package/src/cli.ts +56 -56
  31. package/src/config/config.ts +14 -0
  32. package/src/contracts.ts +38 -30
  33. package/src/cron/cron-jobs.ts +4 -3
  34. package/src/cron/cron-pr-intake.ts +1 -2
  35. package/src/extension.ts +69 -24
  36. package/src/gateway/gateway-client.ts +24 -15
  37. package/src/group/group-runner.ts +3 -2
  38. package/src/group-runner-extension.ts +7 -3
  39. package/src/host-extension.ts +109 -2
  40. package/src/host-sdk-helper.ts +6 -1
  41. package/src/lane/decision-tool.ts +2 -3
  42. package/src/lane/lane-report.ts +8 -30
  43. package/src/lane/lane-rows.ts +1 -1
  44. package/src/lane/workflow.ts +44 -3
  45. package/src/lane-extension.ts +5 -46
  46. package/src/messaging/discord-context.ts +8 -6
  47. package/src/messaging/discord-work-thread.ts +36 -0
  48. package/src/omp/host-protocol.ts +4 -3
  49. package/src/omp/host.ts +24 -7
  50. package/src/omp/managed-super.ts +43 -27
  51. package/src/omp/native-sessions.ts +12 -0
  52. package/src/omp/worker-memory-import.ts +410 -0
  53. package/src/omp/worker-memory-sdk.ts +8 -0
  54. package/src/operator/setup.ts +8 -13
  55. package/src/pr/pr-github-schema.ts +9 -0
  56. package/src/pr/pr-github.ts +6 -2
  57. package/src/pr/pr-intake-automation.ts +11 -8
  58. package/src/pr/pr-intake-fix.ts +2 -5
  59. package/src/pr/pr-intake-review.ts +7 -7
  60. package/src/routing/topic-history.ts +2 -2
  61. package/src/runtime/controller.ts +720 -468
  62. package/src/runtime/head-recovery.ts +7 -7
  63. package/src/runtime/head-superstack.ts +83 -0
  64. package/src/runtime/result-attachments.ts +3 -1
  65. package/src/runtime/worker-memory.ts +156 -0
  66. package/src/storage/deferred-routing.ts +1 -7
  67. package/src/storage/store.ts +465 -372
  68. package/src/worker/worker-host.ts +3 -2
  69. package/src/worker/worker-ledger.ts +20 -11
  70. package/src/worker/worker-memory-page.ts +83 -0
  71. package/src/worker/worker-memory-proofs.ts +260 -0
  72. package/src/worker/worker-memory-source.ts +305 -0
  73. package/src/worker/worker-memory-storage.ts +130 -0
  74. package/src/worker/worker-profile.ts +2 -0
  75. package/src/worker/worker-repository.ts +92 -7
  76. package/src/worker/worker-request.ts +1 -0
  77. package/src/worker/worker-service.ts +25 -8
  78. package/src/worker/worker-wire.ts +20 -6
@@ -11,6 +11,8 @@ export interface DiscordConfig {
11
11
  allowedChannelIds: string[];
12
12
  readonly requireAddressing?: boolean;
13
13
  readonly editProgressInPlace?: boolean;
14
+ readonly allowCrossChannelThreads?: boolean;
15
+ readonly crossChannelThreadScope?: "allowlist" | "guild";
14
16
  voice?: DiscordVoiceConfig;
15
17
  }
16
18
 
@@ -73,6 +75,7 @@ export interface Config {
73
75
  maxSubagents: number;
74
76
  idleMs: number;
75
77
  readonly headIdleMs?: number;
78
+ readonly remoteMemorySync?: boolean;
76
79
  model?: string;
77
80
  discord?: DiscordConfig;
78
81
  telegram?: TelegramConfig;
@@ -243,6 +246,14 @@ export function parseConfig(value: unknown, path: string): Config {
243
246
  const editProgressInPlace = discord?.editProgressInPlace;
244
247
  if (editProgressInPlace !== undefined && typeof editProgressInPlace !== "boolean")
245
248
  throw new Error("discord.editProgressInPlace must be a boolean");
249
+ const allowCrossChannelThreads = discord?.allowCrossChannelThreads;
250
+ if (allowCrossChannelThreads !== undefined && typeof allowCrossChannelThreads !== "boolean")
251
+ throw new Error("discord.allowCrossChannelThreads must be a boolean");
252
+ const crossChannelThreadScope = discord?.crossChannelThreadScope;
253
+ if (crossChannelThreadScope !== undefined && crossChannelThreadScope !== "allowlist" && crossChannelThreadScope !== "guild")
254
+ throw new Error("discord.crossChannelThreadScope must be allowlist or guild");
255
+ if (raw.remoteMemorySync !== undefined && typeof raw.remoteMemorySync !== "boolean")
256
+ throw new Error("remoteMemorySync must be a boolean");
246
257
  const voice = discord?.voice === undefined ? undefined : record(discord.voice, "discord.voice");
247
258
  let voiceConfig: DiscordVoiceConfig | undefined;
248
259
  if (voice) {
@@ -286,6 +297,7 @@ export function parseConfig(value: unknown, path: string): Config {
286
297
  maxSubagents,
287
298
  idleMs: integer(raw.idleMs, "idleMs", 0),
288
299
  headIdleMs: raw.headIdleMs === undefined ? DEFAULT_HEAD_IDLE_MS : integer(raw.headIdleMs, "headIdleMs", 0),
300
+ ...(raw.remoteMemorySync === true && { remoteMemorySync: true }),
289
301
  ...(raw.model === undefined ? {} : { model: text(raw.model, "model") }),
290
302
  ...(discord ? { discord: {
291
303
  tokenEnv: tokenEnv(discord.tokenEnv, "discord.tokenEnv"),
@@ -294,6 +306,8 @@ export function parseConfig(value: unknown, path: string): Config {
294
306
  allowedChannelIds: discordChannels,
295
307
  requireAddressing: requireAddressing ?? false,
296
308
  editProgressInPlace: editProgressInPlace ?? false,
309
+ allowCrossChannelThreads: allowCrossChannelThreads ?? false,
310
+ crossChannelThreadScope: crossChannelThreadScope ?? "allowlist",
297
311
  ...(voiceConfig ? { voice: voiceConfig } : {}),
298
312
  } } : {}),
299
313
  ...(telegram ? { telegram: {
package/src/contracts.ts CHANGED
@@ -57,8 +57,10 @@ export function deferredRecoveryCandidate(text: string) {
57
57
  return { kind: "lane-stop", laneId: argument } as const;
58
58
  }
59
59
 
60
- /** Internal HEAD review ID prefix; authority lives in the current store binding. */
61
- export const SCOPE_REVIEW_PREFIX = "scope-review:";
60
+ /** Reserved legacy synthetic identities; never a source of work or authority. */
61
+ export function isRetiredScopeInput(id: string): boolean {
62
+ return id.startsWith("scope-review:") || id.startsWith("handoff:scope-review:");
63
+ }
62
64
 
63
65
  /** Exact successor generation reserved when a submitted card is authorized to restore its original lane session. */
64
66
  export const laneModelPickerRestoreKey = (sourceId: string) => `lane-model:picker-restore:${sourceId}`;
@@ -304,7 +306,7 @@ export interface OutputRecord {
304
306
  sourceId: string;
305
307
  route: Route;
306
308
  /** Durable original owner message, only in the same physical conversation. */
307
- replyTo?: MessageReference;
309
+ replyTo?: MessageReference & { readonly requireExisting?: true };
308
310
  /** Discord status message replaced in place; fixed when the output is claimed. */
309
311
  readonly editOf?: MessageReference;
310
312
  /** Initial Discord status message; overflow falls back to one attachment instead of multi-message split. */
@@ -318,24 +320,12 @@ export interface OutputRecord {
318
320
  }
319
321
 
320
322
  export type SettlementOutput = Pick<OutputRecord, "id" | "text" | "picker"> & {
323
+ /** Physically distinct Discord HEAD steers proved to precede this shared answer. */
324
+ readonly discordHeadFollowups?: readonly string[];
321
325
  /** Controller-only lane failure routing, never derived from output text. */
322
326
  readonly laneFailure?: "quota" | "recover";
323
- /** Controller-verified clean native settlement of a solo scope-review admission. */
324
- readonly scopeReviewEligible?: boolean;
325
327
  };
326
328
 
327
- export interface ScopeReview {
328
- readonly lane: Lane;
329
- readonly original: InputRecord;
330
- readonly handoff: InputRecord;
331
- }
332
-
333
- /** Controller-proven successful native report, with its exact own approval if one was required. */
334
- export interface ScopeReviewNativeProof {
335
- readonly toolCallId: string;
336
- readonly approvalId?: string;
337
- }
338
-
339
329
  export interface LaneRecoveryScope {
340
330
  readonly lane: Lane;
341
331
  readonly failed: InputRecord;
@@ -398,6 +388,11 @@ export interface HeadRecoveryEffect {
398
388
  state: string;
399
389
  }
400
390
 
391
+ /** A known failure is terminal; an unrecognized state is not evidence of settlement. */
392
+ export function headRecoveryEffectsSettled(effects: readonly HeadRecoveryEffect[]): boolean {
393
+ return effects.every(({ state }) => state === "sent" || state === "complete" || state === "failed");
394
+ }
395
+
401
396
  /** Ordered HEAD receipts for owner inputs still waiting for topic routing. */
402
397
  export interface DeferredRoutingPort {
403
398
  enqueue(input: Inbound): void;
@@ -424,12 +419,6 @@ export interface StorePort {
424
419
  ownerSource(id: string): InputRecord | null;
425
420
  /** Revalidate a report's exact failed admission, actionable owner and operator selection. */
426
421
  laneRecoveryScope(reportId: string): LaneRecoveryScope | null;
427
- /** Stage a verified direct native scope-review signal; does not enqueue a HEAD input. */
428
- recordScopeReview(inputId: string, generation: number, sessionId: string, sourceId: string, proof: ScopeReviewNativeProof): boolean;
429
- /** Verify the current owner request, solo admission, and lane binding for review or granted dispatch. */
430
- scopeReview(reviewId: string): ScopeReview | null;
431
- /** Record one HEAD intent; only eligible native settlement can admit corrective work. */
432
- requestScopeCorrection(reviewId: string): string;
433
422
  /** Original parent route for a redirected report or a handoff derived from that report. */
434
423
  reportApprovalSource(id: string): InputRecord | null;
435
424
  /** Manager handoff's verified reply route, pinned for a parent-origin thread follow-up or a joined bound reply. */
@@ -448,9 +437,11 @@ export interface StorePort {
448
437
  latestLaneRun(target: string): InputRecord | null;
449
438
  /** A successful lane run still has an unresolved final report or delivery. */
450
439
  hasPendingLaneResult(target: string): boolean;
451
- /** A current scope review or granted correction still needs this lane generation. */
452
- hasPendingScopeReview(target: string): boolean;
453
440
  hasPendingLanePlacement(target: string): boolean;
441
+ /** Check both transfer endpoints without reading their queued messages or private dialog contents. */
442
+ hasWorkerMemoryHold(target: string): boolean;
443
+ /** Optional maintenance must never wait for a competing Gateway writer. */
444
+ tryWorkerMemoryMeta(keys: string | readonly string[], value: string): boolean;
454
445
  /** An uncertain HEAD input with a nonempty original native-owner record. */
455
446
  hasHeadRecoveryInput(): boolean;
456
447
  /** No automatic head replacement while an original HEAD delivery is unresolved. */
@@ -460,6 +451,8 @@ export interface StorePort {
460
451
  kickoffHold(target: string): KickoffHold | null;
461
452
  /** The first authorized revision on the physical route, even after settlement. */
462
453
  firstAdmittedMessage(route: Route, messageId: string): InputRecord | null;
454
+ /** A physically later owner message (or revision of this original) was already admitted in this exact topic. */
455
+ isLateTopicOriginal(source: InputRecord): boolean;
463
456
  /** Exact logical child of a parent reply; unverified evidence must not select a stop target. */
464
457
  repliedParentTopic(route: Route, messageId: string): Lane | "unverified" | null;
465
458
  /** Workspace evidenced by a placed owner message or a confirmed bot reply on this physical route. */
@@ -478,6 +471,11 @@ export interface StorePort {
478
471
  admittedMessageIds(route: Route): Iterable<string>;
479
472
  bindInput(id: string, target: string): void;
480
473
  submit(id: string, requestId: string, generation: number): boolean;
474
+ /** Reopen the verified lane and submit its goal resume together, without admitting a prompt. */
475
+ submitGoalResume(input: Inbound, target: string, sourceId: string, owner: {
476
+ requestId: string; generation: number; sessionId: string; sessionFile: string; cursor: string | null; goalId?: string;
477
+ scopedWorkOwnerId?: string;
478
+ }, priorWorkState?: Lane["workState"]): InputRecord;
481
479
  /** Nonterminal native assistant observation; never settles or dispatches its owner. */
482
480
  progress(id: string, generation: number, sessionId: string, eventId: string, text: string, editInPlace?: boolean): boolean;
483
481
  recordLaneReport(id: string, generation: number, sessionId: string, eventId: string, report: LaneReport, observedAt?: number): boolean;
@@ -516,6 +514,16 @@ export interface StorePort {
516
514
  putApproval(approval: Approval, ownerInputId?: string): void;
517
515
  approval(id: string): Approval | null;
518
516
  approvals(target?: string): Approval[];
517
+ /** No Messenger card or automatic native response for a retired approval or its unresolved admission. */
518
+ isNativeApprovalHeld(owner: {
519
+ readonly target: string; readonly generation: number; readonly sessionId: string;
520
+ readonly input?: { readonly id: string; readonly sessionFile: string };
521
+ }, approvalId: string): boolean;
522
+ /** Retired card identities whose original remote dismissal is not yet confirmed. */
523
+ retiredApprovalDismissals(): string[];
524
+ /** Consume the one dismissal attempt only when there is an exact remote card receipt. */
525
+ claimRetiredApprovalDismissal(id: string): Approval | null;
526
+ finishRetiredApprovalDismissal(id: string): void;
519
527
  resolveApproval(id: string, generation: number, state: "answered" | "cancelled", resolution?: ApprovalResolution): boolean;
520
528
  setApprovalMessage(id: string, remoteId: string): void;
521
529
  recoverDeliveries(): void;
@@ -608,17 +616,17 @@ export interface Messenger {
608
616
  }): Promise<void>;
609
617
  send(output: OutputRecord): Promise<string>;
610
618
  sendGroup?(reply: GroupReply): Promise<string>;
611
- /** Verify the authenticated adapter. History is read-only and may run before intake is acknowledged. */
612
- assertRoute?(route: Route, purpose?: "history"): void | Promise<void>;
619
+ /** Read-only checks for history and already-admitted bound work do not require a drained Gateway queue. */
620
+ assertRoute?(route: Route, purpose?: "history" | "bound-work"): void | Promise<void>;
613
621
  /** Cosmetic own reactions on the original message; never an admission or completion receipt. */
614
622
  setActivity?(message: MessageReference, activity: MessageActivity): Promise<void>;
615
623
  showApproval(approval: Approval): Promise<string>;
616
624
  dismissApproval(approval: Approval): Promise<void>;
617
625
  /** Read-only authenticated capability probe; false is unsupported, not a failed creation. */
618
- canCreateThread?(route: Route, appliedTags?: readonly string[]): Promise<boolean>;
619
- createThread(route: Route, title: string, sourceMessageId?: string, appliedTags?: readonly string[]): Promise<Route>;
626
+ canCreateThread?(route: Route, appliedTags?: readonly string[], placementSource?: Route): Promise<boolean>;
627
+ createThread(route: Route, title: string, sourceMessageId?: string, appliedTags?: readonly string[], placementSource?: Route): Promise<Route>;
620
628
  /** Optional native thread management; unsupported transports must not simulate it. */
621
- inspectThread?(route: Route): Promise<ThreadInfo>;
629
+ inspectThread?(route: Route, placementSource?: Route): Promise<ThreadInfo>;
622
630
  updateThread?(route: Route, update: ThreadUpdate): Promise<ThreadInfo>;
623
631
  inspectDiscordContext?(route: Route): Promise<DiscordContext>;
624
632
  discordPurpose?(request: DiscordPurposeRequest): Promise<readonly DiscordPurposeNote[]>;
@@ -87,6 +87,10 @@ export interface CronUpdate {
87
87
  readonly cancelPending?: string;
88
88
  }
89
89
 
90
+ function reject(text: string): CronUpdate {
91
+ return { text, state: "cancelled" };
92
+ }
93
+
90
94
  function jobMetadata(state: CronState, changed: CronJob, remove = false) {
91
95
  const next = state.jobs.filter(job => job.id !== changed.id);
92
96
  if (!remove) next.push(changed);
@@ -379,7 +383,6 @@ export class CronJobs {
379
383
  }
380
384
 
381
385
  private addPrJob(input: InputRecord, tail: string, now: number): CronUpdate {
382
- const reject = (text: string): CronUpdate => ({ text, state: "cancelled" });
383
386
  const source = this.prControlSource(input.id);
384
387
  if (!source || routeKey(source.route) !== routeKey(input.route)) {
385
388
  return reject("PR intake requires a new authenticated owner command in a Discord guild parent channel.");
@@ -434,7 +437,6 @@ export class CronJobs {
434
437
  }
435
438
 
436
439
  private setPrMode(input: InputRecord, argument: string): CronUpdate {
437
- const reject = (text: string): CronUpdate => ({ text, state: "cancelled" });
438
440
  const source = this.prControlSource(input.id);
439
441
  if (source?.state !== "pending" || routeKey(source.route) !== routeKey(input.route)) {
440
442
  return reject("Changing PR intake mode requires a new authenticated owner command in its Discord guild parent channel.");
@@ -486,7 +488,6 @@ export class CronJobs {
486
488
 
487
489
  control(input: InputRecord, argument: string, now: number): CronUpdate {
488
490
  const [, action = "", tail = ""] = /^(\S+)(?:\s+([\s\S]*))?$/.exec(argument) ?? [];
489
- const reject = (text: string): CronUpdate => ({ text, state: "cancelled" });
490
491
  if (!action || action === "help" && !tail) return { text: usage };
491
492
  const state = this.state();
492
493
  const scoped = state.jobs.flatMap(job => {
@@ -86,9 +86,8 @@ function offerText(repository: string, candidate: CronPrCandidate): string {
86
86
  }
87
87
 
88
88
  export function describePrIntake(store: StorePort, job: CronPrJob, number: number | null): string {
89
- const candidates = ledger(store, job.repository)?.candidates.filter(candidate => candidate.jobId === job.id) ?? [];
89
+ const newest = ledger(store, job.repository)?.candidates.filter(candidate => candidate.jobId === job.id).reverse() ?? [];
90
90
  const summary = job.lastRunId ? store.getMeta(outcomeKey(job.lastRunId)) : null;
91
- const newest = [...candidates].reverse();
92
91
  const selected = number === null ? newest.slice(0, 10) : newest.filter(candidate => candidate.number === number);
93
92
  const open = !job.paused && !job.removed && job.stopBoundary === store.getMeta("head:stop-boundary");
94
93
  const lines = selected.map(candidate => {
package/src/extension.ts CHANGED
@@ -3,6 +3,7 @@ import { fileURLToPath } from "node:url";
3
3
  import { join } from "node:path";
4
4
  import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
5
5
  import { Settings } from "@oh-my-pi/pi-coding-agent/config/settings";
6
+ import { loadLegacyPiModule } from "@oh-my-pi/pi-coding-agent/extensibility/plugins/legacy-pi-compat";
6
7
  import { Type } from "@sinclair/typebox";
7
8
  import { configuredPlatforms, hostPaths, loadConfigSnapshot } from "./config/config";
8
9
  import { loadWakeConfig } from "./config/wake-config";
@@ -28,6 +29,38 @@ import { soulUpdateSchema } from "./omp/soul";
28
29
  // from this package so a same-name workspace skill cannot change the procedure.
29
30
  const headInstructions = readFileSync(new URL("../skills/head/SKILL.md", import.meta.url), "utf8");
30
31
  const headReferenceDirectory = fileURLToPath(new URL("../skills/head/references", import.meta.url));
32
+
33
+ type WorkerMemoryModule = typeof import("./omp/worker-memory-import");
34
+ type WorkerMemorySdk = typeof import("./omp/worker-memory-sdk");
35
+
36
+ function workerMemoryModule(value: unknown): value is WorkerMemoryModule {
37
+ return !!value && typeof value === "object" && "prepareWorkerMemoryImport" in value
38
+ && typeof value.prepareWorkerMemoryImport === "function";
39
+ }
40
+
41
+ function workerMemorySdk(value: unknown): value is WorkerMemorySdk {
42
+ const functions: ReadonlyArray<keyof WorkerMemorySdk> = ["computeMnemopiBankScope", "fastembedModelName",
43
+ "withMnemopiRuntimeOptions", "getMnemopiRuntimeOptions", "embed", "insertLiveEmbeddings"];
44
+ return !!value && typeof value === "object"
45
+ && functions.every(key => typeof Reflect.get(value, key) === "function");
46
+ }
47
+
48
+ async function loadWorkerMemoryDestination() {
49
+ const options = { reload: false };
50
+ try {
51
+ const [sdk, memory] = await Promise.all([
52
+ loadLegacyPiModule(fileURLToPath(new URL("../.upstream/worker-memory-sdk.mjs", import.meta.url)), options),
53
+ loadLegacyPiModule(fileURLToPath(new URL("./omp/worker-memory-import.ts", import.meta.url)), options),
54
+ ]);
55
+ if (workerMemorySdk(sdk) && workerMemoryModule(memory))
56
+ return (session: Parameters<WorkerMemoryModule["prepareWorkerMemoryImport"]>[0], cwd: string) =>
57
+ memory.prepareWorkerMemoryImport(session, cwd, sdk);
58
+ } catch (error) {
59
+ if (!(error instanceof Error)) throw error;
60
+ // Optional capability: don't activate a remote-memory lane without it.
61
+ }
62
+ }
63
+
31
64
  const managerTools: Record<string, true> = {
32
65
  head_recovery: true, head_set_model: true, cron_create: true, soul_update: true,
33
66
  lane_models: true, lane_init_presets: true, lane_set_model: true, lane_review_decision: true,
@@ -45,11 +78,24 @@ const result = (value: unknown) => ({
45
78
  content: [{ type: "text" as const, text: typeof value === "string" ? value : JSON.stringify(value, null, 2) }],
46
79
  details: {},
47
80
  });
48
- const workflowSchema = Type.Optional(Type.Object({
81
+ const workflowSelection = Type.Object({
49
82
  name: Type.Union(WORKFLOW_NAMES.map(name => Type.Literal(name))),
50
83
  reason: Type.String({ minLength: 1 }),
51
- }, { additionalProperties: false }));
84
+ }, { additionalProperties: false });
85
+ const workflowSchema = Type.Optional(workflowSelection);
86
+ const laneModelSelection = {
87
+ model: Type.Optional(Type.Object({ provider: Type.String({ minLength: 1 }), id: Type.String({ minLength: 1 }) })),
88
+ preset: Type.Optional(Type.String({ minLength: 1 })),
89
+ modelReason: Type.String({ minLength: 1 }),
90
+ } as const;
52
91
  const threadTagsSchema = Type.Array(Type.String({ pattern: "^[0-9]{1,20}$" }), { maxItems: 5, uniqueItems: true });
92
+ const laneRouteSchema = Type.Object({
93
+ platform: Type.Union([Type.Literal("discord"), Type.Literal("telegram"), Type.Literal("slack"), Type.Literal("kakao")]),
94
+ accountId: Type.String(), authorityId: Type.String(),
95
+ guildId: Type.Union([Type.String(), Type.Null()]), channelId: Type.String(),
96
+ threadId: Type.Union([Type.String(), Type.Null()]),
97
+ topicId: Type.Optional(Type.String()),
98
+ });
53
99
  const threadTitleSchema = Type.String({ minLength: 1, maxLength: 100, pattern: "\\S" });
54
100
  const threadChangeFields = {
55
101
  title: Type.Optional(threadTitleSchema),
@@ -135,8 +181,6 @@ export default function superagentExtension(pi: ExtensionAPI): void {
135
181
  pi.on("tool_call", (event, ctx) => {
136
182
  if (runtime?.laneDecisionReviewActive() && (ctx.agent.kind !== "main" || event.toolName !== "lane_review_decision"))
137
183
  return { block: true, reason: "A lane question permits only answering or escalating its original decision" };
138
- if (runtime?.scopeReviewActive() && (ctx.agent.kind !== "main" || event.toolName !== "lane_message"))
139
- return { block: true, reason: "This assignment review permits only a direct same-lane correction from its verified owner message" };
140
184
  if (event.toolName === "soul_update") {
141
185
  try { requireRuntime(ctx).authorizeSoulUpdate(event.input, ctx.sessionManager.getSessionId()); }
142
186
  catch (error) {
@@ -168,8 +212,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
168
212
  return { block: true, reason: "HEAD recovery is restricted to the original main head" };
169
213
  if (["cron_create", "decision_list", "decision_inspect", "decision_withdraw"].includes(event.toolName) && ctx.agent.kind !== "main")
170
214
  return { block: true, reason: "Lane management is restricted to the main superagent head" };
171
- if (!runtime?.headRecoveryActive()) return;
172
- if (ctx.agent.kind !== "main" || event.toolName !== "head_recovery") {
215
+ if (runtime?.headRecoveryActive() && (ctx.agent.kind !== "main" || event.toolName !== "head_recovery")) {
173
216
  runtime.blockHeadRecoveryTool();
174
217
  return { block: true, reason: "The isolated HEAD recovery turn permits only head_recovery; original work is not replayed" };
175
218
  }
@@ -320,13 +363,11 @@ export default function superagentExtension(pi: ExtensionAPI): void {
320
363
  });
321
364
  pi.registerTool({
322
365
  name: "lane_start", label: "Start independent work", loadMode: "essential", approval: "exec",
323
- description: "Bind an independent topic to its own OMP session at an explicit cwd. By default create a supported native thread/topic, or reuse the source's existing binding; unsupported private chats use a logical topic. For a clearly new topic inside an existing thread, supply its same authorized parent as destination with threadId:null and no topicId to create a sibling. An existing independent destination binds directly. Do not ask the user to run /new merely to create a topic. Consult lane_models and native judge; choose exactly one model {provider,id} or native preset name, with concise modelReason. The resolved model and full preset snapshot persist; retries/global edits do not retarget the lane. Optional workflow {name,reason} is explicit head selection within the user's authorized objective, never inferred from brief/report prose. It binds to this source/handoff; conflicting retries reject. Native capability/permissions own activation; selecting SUPER through RPC does not create a goal. Returns queued identity, not completion. Small main work stays direct. sourceId is the original trusted request ID.",
366
+ description: "Bind an independent topic to its own OMP session at an explicit cwd. By default create a supported native thread/topic, or reuse the source's existing binding; unsupported private chats use a logical topic. For a clearly new topic inside an existing thread, supply an authorized parent as destination with threadId:null and no topicId to create a sibling. Use the source parent unless discord.allowCrossChannelThreads is enabled. In the same Discord guild, the default scope allows listed parents; explicit guild scope additionally permits a supported parent that the bot can use. Out-of-list placements do not accept new requests there. An existing independent destination binds directly only under the ordinary route policy. Do not ask the user to run /new merely to create a topic. Consult lane_models and native judge; choose exactly one model {provider,id} or native preset name, with concise modelReason. The resolved model and full preset snapshot persist; retries/global edits do not retarget the lane. Optional workflow {name,reason} is explicit head selection within the user's authorized objective, never inferred from brief/report prose. It binds to this source/handoff; conflicting retries reject. Native capability/permissions own activation; selecting SUPER through RPC does not create a goal. Returns queued identity, not completion. Small main work stays direct. sourceId is the original trusted request ID.",
324
367
  parameters: Type.Object({
325
368
  sourceId: Type.String(), title: Type.String(), cwd: Type.String(),
326
369
  kickoff: Type.String({ minLength: 1, description: "A concise message in the user's language stating the concrete approach. Delivered in the work topic before native lane execution; failed or uncertain delivery holds execution." }),
327
- model: Type.Optional(Type.Object({ provider: Type.String({ minLength: 1 }), id: Type.String({ minLength: 1 }) })),
328
- preset: Type.Optional(Type.String({ minLength: 1 })),
329
- modelReason: Type.String({ minLength: 1 }),
370
+ ...laneModelSelection,
330
371
  brief: Type.Optional(Type.String()), acceptance: Type.Optional(Type.Array(Type.String())),
331
372
  workflow: workflowSchema,
332
373
  placement: Type.Optional(Type.Object({
@@ -338,13 +379,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
338
379
  description: "Execution location for new work at the verified local cwd. Omit for local or an eligible operator-configured default. Remote, platform, or worker requires an approved paired worker and a clean committed Git checkout, with no local fallback. A bound worker can hold execution until ready. Local opts out and cannot be combined with platform or worker.",
339
380
  })),
340
381
  appliedTags: Type.Optional(threadTagsSchema),
341
- destination: Type.Optional(Type.Object({
342
- platform: Type.Union([Type.Literal("discord"), Type.Literal("telegram"), Type.Literal("slack"), Type.Literal("kakao")]),
343
- accountId: Type.String(), authorityId: Type.String(),
344
- guildId: Type.Union([Type.String(), Type.Null()]), channelId: Type.String(),
345
- threadId: Type.Union([Type.String(), Type.Null()]),
346
- topicId: Type.Optional(Type.String()),
347
- })),
382
+ destination: Type.Optional(laneRouteSchema),
348
383
  }),
349
384
  async execute(_id, params, _signal, _onUpdate, ctx) { return result(await requireRuntime(ctx).startLane(params)); },
350
385
  });
@@ -382,12 +417,13 @@ export default function superagentExtension(pi: ExtensionAPI): void {
382
417
  });
383
418
  pi.registerTool({
384
419
  name: "thread_inspect", label: "Inspect Discord forum or thread", approval: "read",
385
- description: "Read the original user source's Discord guild channel/thread, or an explicitly selected managed lane's thread. Returns available tag IDs, required-tag policy, applied tags, title and archive state. Use before selecting appliedTags for lane_start. This never creates a topic or changes lane state.",
420
+ description: "Read the original user source's Discord guild channel/thread, an explicitly selected managed lane's thread, or an eligible alternate guild parent (destination with threadId:null and no topicId, instead of laneId). Returns available tag IDs, required-tag policy, applied tags, title and archive state. Use before selecting appliedTags for lane_start. This never creates a topic, changes lane state, or reads message history.",
386
421
  parameters: Type.Object({
387
422
  sourceId: Type.String({ minLength: 1 }), laneId: Type.Optional(Type.String({ minLength: 1 })),
423
+ destination: Type.Optional(laneRouteSchema),
388
424
  }, { additionalProperties: false }),
389
425
  async execute(_id, params, _signal, _onUpdate, ctx) {
390
- return result(await requireRuntime(ctx).inspectThread(params.sourceId, params.laneId));
426
+ return result(await requireRuntime(ctx).inspectThread(params.sourceId, params.laneId, params.destination));
391
427
  },
392
428
  });
393
429
  pi.registerTool({
@@ -448,9 +484,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
448
484
  description: "Explicitly change one idle lane's model or full native preset snapshot without changing global OMP settings, the head, or other lanes. Requires a received authorized sourceId, exactly one model/preset and modelReason. Refuses active work, approvals/services/goals or unresolved submissions. Uses durable intent and native readback; do not blindly repeat an uncertain change.",
449
485
  parameters: Type.Object({
450
486
  id: Type.String(), sourceId: Type.String(),
451
- model: Type.Optional(Type.Object({ provider: Type.String({ minLength: 1 }), id: Type.String({ minLength: 1 }) })),
452
- preset: Type.Optional(Type.String({ minLength: 1 })),
453
- modelReason: Type.String({ minLength: 1 }),
487
+ ...laneModelSelection,
454
488
  }),
455
489
  async execute(_id, params, _signal, _onUpdate, ctx) { return result(await requireRuntime(ctx).changeModel(params)); },
456
490
  });
@@ -486,9 +520,12 @@ export default function superagentExtension(pi: ExtensionAPI): void {
486
520
  pi.registerTool({
487
521
  name: "lane_message", label: "Message independent work", loadMode: "essential", approval: "exec",
488
522
  description: "Durably admit a follow-up to a specific open lane. For an original owner request from the exact guild parent of the lane's physical Discord thread, HEAD-reviewed progress and final reports go to that thread, not the parent. Do not duplicate them. Returns its input ID and durable state; pending work reports runtime blocks, blocking uncertain input IDs, and any unconfirmed kickoff. Report such holds instead of retrying. Ordinary same-topic follow-ups steer an eligible active native run by default; ineligible work stays queued. Do not require a separate user /steer command. sourceId identifies the original received user instruction for duplicate suppression. Optional workflow {name,reason} is explicit head selection within that objective; text/quotes/reports never select one. Workflow selections remain serialized, not steered into an active run. The exact workflow/source/handoff is durable and conflicting retries reject. Admission is not execution or completion.",
489
- parameters: Type.Object({ id: Type.String(), text: Type.String(), sourceId: Type.String(), workflow: workflowSchema }),
523
+ parameters: Type.Object({
524
+ id: Type.String(), text: Type.String(), sourceId: Type.String(),
525
+ workflow: Type.Optional(Type.Union([workflowSelection, Type.Null({ description: "No explicit workflow; use ordinary lane dispatch." })])),
526
+ }),
490
527
  async execute(_id, params, _signal, _onUpdate, ctx) {
491
- return result(await requireRuntime(ctx).messageLane(params.id, params.text, params.sourceId, params.workflow));
528
+ return result(await requireRuntime(ctx).messageLane(params.id, params.text, params.sourceId, params.workflow ?? undefined));
492
529
  },
493
530
  });
494
531
  pi.registerTool({
@@ -537,6 +574,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
537
574
  throw new Error("Gateway configuration changed before replacement HEAD initialization");
538
575
  const { config } = snapshot;
539
576
  delete process.env.OMP_SUPERAGENT_RESTART_CONFIG_SHA256;
577
+ const workerMemory = config.remoteMemorySync ? await loadWorkerMemoryDestination() : undefined;
540
578
  const store = new Store(join(config.stateDir, "coordination.sqlite"));
541
579
  let messenger: ReturnType<typeof createGatewayMessenger>;
542
580
  try {
@@ -555,6 +593,13 @@ export default function superagentExtension(pi: ExtensionAPI): void {
555
593
  pi.logger.error(`Superagent: ${error instanceof Error ? error.message : String(error)}`);
556
594
  }, {
557
595
  topicMemory: ctx.memory,
596
+ workerMemoryDestination: (id, file, cwd) => {
597
+ const root = pi.pi.AgentRegistry.global().get(pi.pi.MAIN_AGENT_ID);
598
+ const session = root?.session;
599
+ return root?.id === ctx.agent.id && session instanceof pi.pi.AgentSession
600
+ && session.sessionId === id && session.sessionFile === file && cwd === ctx.cwd
601
+ ? workerMemory?.(session, cwd) : undefined;
602
+ },
558
603
  readHeadQuota: (failure, sessionId, signal) => {
559
604
  const session = pi.pi.AgentRegistry.global().get(pi.pi.MAIN_AGENT_ID)?.session;
560
605
  return session instanceof pi.pi.AgentSession && session.sessionId === sessionId
@@ -13,7 +13,7 @@ import type { GroupReply } from "../group/group-policy";
13
13
  import type { DiscordPresenceStatus, MessengerPresenceRequest } from "../contracts";
14
14
 
15
15
  export interface GatewayHeadMessenger extends Messenger {
16
- assertRoute(route: Route, purpose?: "history"): Promise<void>;
16
+ assertRoute(route: Route, purpose?: "history" | "bound-work"): Promise<void>;
17
17
  requestRestart(request: GatewayRestartRequest): Promise<GatewayRestartRecord>;
18
18
  }
19
19
 
@@ -28,6 +28,11 @@ function retryableReconnect(error: unknown): boolean {
28
28
  return retryableHandshake(error) || (error instanceof DeliveryError && error.certainty === "uncertain");
29
29
  }
30
30
 
31
+ function stableEffectId(parts: readonly string[]): string {
32
+ const hash = createHash("sha256").update(JSON.stringify(parts)).digest("hex");
33
+ return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20, 32)}`;
34
+ }
35
+
31
36
  /** Transport-only head adapter. Detaching never logs out the actual accounts. */
32
37
  class GatewayMessenger implements GatewayHeadMessenger {
33
38
  readonly managesStartupHistory = true;
@@ -192,45 +197,49 @@ class GatewayMessenger implements GatewayHeadMessenger {
192
197
  }
193
198
  }
194
199
 
195
- private effect<T>(operation: string, args: unknown[]): Promise<T> {
196
- return this.call<T>("/effect", { id: crypto.randomUUID(), operation, args });
200
+ private effect<T>(operation: string, args: unknown[], id: string = crypto.randomUUID()): Promise<T> {
201
+ return this.call<T>("/effect", { id, operation, args });
197
202
  }
198
203
  sendGroup(reply: GroupReply): Promise<string> {
199
- const hash = createHash("sha256").update(JSON.stringify(["group-reply", reply.sourceId, reply.outcome])).digest("hex");
200
- const id = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20, 32)}`;
201
- return this.call<string>("/effect", { id, operation: "sendGroup", args: [reply] });
204
+ return this.effect("sendGroup", [reply], stableEffectId(["group-reply", reply.sourceId, reply.outcome]));
202
205
  }
203
206
  requestRestart(request: GatewayRestartRequest): Promise<GatewayRestartRecord> { return this.call("/restart", request); }
204
207
  send(output: OutputRecord): Promise<string> {
205
208
  const { resultAttachment } = output;
206
209
  if (!resultAttachment) return this.effect("send", [output]);
207
210
  // Stable across client reattachment; the Gateway journals the one attempt.
208
- const hash = createHash("sha256").update(JSON.stringify(["result-attachment", output.id])).digest("hex");
209
- const id = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20, 32)}`;
211
+ const id = stableEffectId(["result-attachment", output.id]);
210
212
  // Transfer only a receipt; the old persisted payload is read by the Gateway
211
213
  // itself so its original attempt fingerprint can still be reconciled.
212
214
  const { payload } = resultAttachment;
213
- return this.call<string>("/effect", { id, operation: "send", args: [{
215
+ return this.effect("send", [{
214
216
  id: output.id, route: output.route, text: output.text, replyTo: output.replyTo,
215
217
  resultAttachment: "data" in payload ? { name: payload.name, legacy: true } : payload,
216
- }] });
218
+ }], id);
217
219
  }
218
- assertRoute(route: Route, purpose?: "history"): Promise<void> {
219
- return this.call(purpose === "history" ? "/history/route" : "/route", { route }, AbortSignal.timeout(1000));
220
+ assertRoute(route: Route, purpose?: "history" | "bound-work"): Promise<void> {
221
+ return this.call(purpose === "history" || purpose === "bound-work" ? "/history/route" : "/route", { route }, AbortSignal.timeout(1000));
220
222
  }
221
223
  setActivity(message: MessageReference, activity: MessageActivity): Promise<void> {
222
224
  return this.effect("setActivity", [{ route: message.route, messageId: message.messageId }, activity]);
223
225
  }
224
226
  showApproval(approval: Approval): Promise<string> { return this.effect("showApproval", [approval]); }
225
227
  dismissApproval(approval: Approval): Promise<void> { return this.effect("dismissApproval", [approval]); }
226
- canCreateThread(route: Route, appliedTags?: readonly string[]): Promise<boolean> {
228
+ canCreateThread(route: Route, appliedTags?: readonly string[], placementSource?: Route): Promise<boolean> {
229
+ if (placementSource) return this.effect("canCreateThread", [route, appliedTags ?? null, placementSource]);
227
230
  return this.effect("canCreateThread", appliedTags === undefined ? [route] : [route, appliedTags]);
228
231
  }
229
- createThread(route: Route, title: string, sourceMessageId?: string, appliedTags?: readonly string[]): Promise<Route> {
232
+ createThread(route: Route, title: string, sourceMessageId?: string, appliedTags?: readonly string[], placementSource?: Route): Promise<Route> {
233
+ if (placementSource) {
234
+ if (sourceMessageId !== undefined) throw new Error("Cross-channel threads cannot use a source message");
235
+ return this.effect("createThread", [route, title, null, appliedTags ?? null, placementSource]);
236
+ }
230
237
  return this.effect("createThread", appliedTags !== undefined ? [route, title, sourceMessageId ?? null, appliedTags]
231
238
  : sourceMessageId !== undefined ? [route, title, sourceMessageId] : [route, title]);
232
239
  }
233
- inspectThread(route: Route): Promise<ThreadInfo> { return this.effect("inspectThread", [route]); }
240
+ inspectThread(route: Route, placementSource?: Route): Promise<ThreadInfo> {
241
+ return this.effect("inspectThread", placementSource ? [route, placementSource] : [route]);
242
+ }
234
243
  updateThread(route: Route, update: ThreadUpdate): Promise<ThreadInfo> { return this.effect("updateThread", [route, update]); }
235
244
  inspectDiscordContext(route: Route): Promise<DiscordContext> { return this.effect("inspectDiscordContext", [route]); }
236
245
  messengerPresence(request: MessengerPresenceRequest): Promise<DiscordPresenceStatus> {
@@ -102,8 +102,9 @@ async function isolatedModel(state: string, selector: string): Promise<string> {
102
102
  const selected = models.map(record).filter(row => row.id === model);
103
103
  if (selected.length !== 1) throw new RestrictedRunError("Restricted model ID must match exactly one model");
104
104
  const { name, reasoning, contextWindow, maxTokens, cost } = selected[0];
105
+ const prices = record(cost);
105
106
  const rates = Object.fromEntries(["input", "output", "cacheRead", "cacheWrite"].map(key => {
106
- const rate = record(cost)[key];
107
+ const rate = prices[key];
107
108
  if (typeof rate !== "number" || !Number.isFinite(rate) || rate < 0) throw new RestrictedRunError("Missing restricted model price");
108
109
  return [key, rate];
109
110
  }));
@@ -212,8 +213,8 @@ function settledResult(output: Buffer, input: Input): { readonly text?: string }
212
213
  if (`${message.provider}/${message.model}` !== input.model || terminalCount !== 0 || !Array.isArray(message.content))
213
214
  return undefined;
214
215
  stopped = message.stopReason === "stop";
215
- const blocks = message.content.map(record);
216
216
  if (input.mode === "chat") {
217
+ const blocks = message.content.map(record);
217
218
  if (!stopped || blocks.some(block => block.type !== "text" && block.type !== "thinking")) return undefined;
218
219
  reply = blocks.flatMap(block => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n").trim();
219
220
  }
@@ -24,14 +24,18 @@ function sameFile(first: Stats, second: Stats): boolean {
24
24
  return first.dev === second.dev && first.ino === second.ino;
25
25
  }
26
26
 
27
+ function eligibleFile(info: Stats): boolean {
28
+ return info.isFile() && info.nlink === 1 && info.size <= maxBytes;
29
+ }
30
+
27
31
  function existingText(path: string): { readonly text: string; readonly mode: number } {
28
32
  const expected = lstatSync(path);
29
- if (!expected.isFile() || expected.nlink !== 1 || expected.size > maxBytes || realpathSync.native(path) !== path)
33
+ if (!eligibleFile(expected) || realpathSync.native(path) !== path)
30
34
  throw new RestrictedPathError("Not an eligible regular text file");
31
35
  const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
32
36
  try {
33
37
  const actual = fstatSync(fd);
34
- if (!sameFile(expected, actual) || !actual.isFile() || actual.nlink !== 1 || actual.size > maxBytes)
38
+ if (!sameFile(expected, actual) || !eligibleFile(actual))
35
39
  throw new RestrictedPathError("File changed or is not an eligible regular file");
36
40
  const buffer = Buffer.alloc(maxBytes + 1);
37
41
  let size = 0;
@@ -111,7 +115,7 @@ export default function groupWorktree(pi: ExtensionAPI): void {
111
115
  if (!isVisibleSegment(entry.name)) continue;
112
116
  const info = lstatSync(join(directory, entry.name));
113
117
  if (info.isDirectory()) names.push(`${entry.name}/`);
114
- else if (info.isFile() && info.nlink === 1 && info.size <= maxBytes) names.push(entry.name);
118
+ else if (eligibleFile(info)) names.push(entry.name);
115
119
  }
116
120
  } finally { handle.closeSync(); }
117
121
  return names.sort().join("\n");