omp-superagent 0.1.10 → 0.1.11

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 (149) hide show
  1. package/DESIGN.md +58 -15
  2. package/README.ko.md +7 -0
  3. package/README.md +7 -0
  4. package/THIRD_PARTY_NOTICES.md +35 -436
  5. package/assets/architecture-dark.svg +7 -12
  6. package/assets/architecture.ko-dark.svg +7 -12
  7. package/assets/architecture.ko.svg +7 -12
  8. package/assets/architecture.mmd +5 -13
  9. package/assets/architecture.svg +7 -12
  10. package/config.example.json +1 -0
  11. package/docs/OPERATIONS.en.md +106 -52
  12. package/docs/OPERATIONS.md +98 -44
  13. package/docs/design/execution.md +80 -52
  14. package/docs/design/messaging.md +113 -32
  15. package/docs/releases/0.1.11.md +18 -0
  16. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  17. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  18. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  19. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  20. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  21. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  22. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  23. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  24. package/package.json +10 -11
  25. package/scripts/{prepare-ulw.ts → prepare-super.ts} +1 -1
  26. package/skills/head/SKILL.md +12 -3
  27. package/skills/head/references/routing.md +1 -1
  28. package/skills/head/references/supervision.md +23 -26
  29. package/skills/lane/SKILL.md +28 -21
  30. package/skills/lane/references/workflow.md +15 -17
  31. package/src/cli.ts +33 -33
  32. package/src/{config.ts → config/config.ts} +7 -3
  33. package/src/config/wake-config.ts +36 -0
  34. package/src/contracts.ts +61 -12
  35. package/src/{cron-jobs.ts → cron/cron-jobs.ts} +21 -13
  36. package/src/{cron-pr-intake.ts → cron/cron-pr-intake.ts} +4 -4
  37. package/src/{cron-schedule.ts → cron/cron-schedule.ts} +3 -3
  38. package/src/extension.ts +43 -25
  39. package/src/{gateway-client.ts → gateway/gateway-client.ts} +89 -32
  40. package/src/{gateway-native.ts → gateway/gateway-native.ts} +4 -4
  41. package/src/{gateway-protocol.ts → gateway/gateway-protocol.ts} +69 -14
  42. package/src/{gateway-wire.ts → gateway/gateway-wire.ts} +12 -7
  43. package/src/gateway-config.ts +1 -1
  44. package/src/gateway-restart-env.ts +3 -3
  45. package/src/{group-access.ts → group/group-access.ts} +8 -3
  46. package/src/{group-policy.ts → group/group-policy.ts} +2 -2
  47. package/src/{group-runner.ts → group/group-runner.ts} +11 -6
  48. package/src/host-extension.ts +164 -36
  49. package/src/host-sdk-helper.ts +62 -65
  50. package/src/{decision-tool.ts → lane/decision-tool.ts} +12 -4
  51. package/src/{decisions.ts → lane/decisions.ts} +12 -10
  52. package/src/{lane-models.ts → lane/lane-models.ts} +1 -1
  53. package/src/{lane-rows.ts → lane/lane-rows.ts} +2 -2
  54. package/src/{lane-watch.ts → lane/lane-watch.ts} +6 -2
  55. package/src/{workflow.ts → lane/workflow.ts} +1 -1
  56. package/src/lane-extension.ts +25 -7
  57. package/src/managed-memory-helper.ts +2 -2
  58. package/src/{managed-ulw-probe.ts → managed-super-probe.ts} +3 -3
  59. package/src/{delivery.ts → messaging/delivery.ts} +1 -1
  60. package/src/{discord-command-registration.ts → messaging/discord-command-registration.ts} +3 -2
  61. package/src/{discord-context.ts → messaging/discord-context.ts} +1 -1
  62. package/src/{messenger-command-catalog.json → messaging/messenger-command-catalog.json} +1 -0
  63. package/src/messaging/messenger-commands.ts +55 -0
  64. package/src/{result-attachment.ts → messaging/result-attachment.ts} +3 -3
  65. package/src/{slack-command-registration.ts → messaging/slack-command-registration.ts} +3 -3
  66. package/src/{telegram-command-registration.ts → messaging/telegram-command-registration.ts} +2 -2
  67. package/src/omp/head-resume.ts +123 -0
  68. package/src/{host-owner-path.ts → omp/host-owner-path.ts} +1 -1
  69. package/src/{host-protocol.ts → omp/host-protocol.ts} +10 -2
  70. package/src/{host-superkit.ts → omp/host-superkit.ts} +1 -1
  71. package/src/{host.ts → omp/host.ts} +26 -17
  72. package/src/{installed-omp.ts → omp/installed-omp.ts} +1 -1
  73. package/src/{managed-memory.ts → omp/managed-memory.ts} +2 -2
  74. package/src/{managed-ulw.ts → omp/managed-super.ts} +42 -16
  75. package/src/omp/native-journal.ts +124 -0
  76. package/src/{native-launch-profile.ts → omp/native-launch-profile.ts} +6 -2
  77. package/src/{native-presets.ts → omp/native-presets.ts} +2 -2
  78. package/src/omp/native-sessions.ts +124 -0
  79. package/src/{omp-usage.ts → omp/omp-usage.ts} +1 -1
  80. package/src/{soul.ts → omp/soul.ts} +2 -2
  81. package/src/omp/stock-head-launch.ts +31 -0
  82. package/src/{autostart.ts → operator/autostart.ts} +3 -3
  83. package/src/{operator.ts → operator/operator.ts} +2 -2
  84. package/src/{setup-judge.ts → operator/setup-judge.ts} +1 -1
  85. package/src/{setup-profiles.ts → operator/setup-profiles.ts} +2 -2
  86. package/src/{setup.ts → operator/setup.ts} +5 -5
  87. package/src/{pr-intake-automation.ts → pr/pr-intake-automation.ts} +1 -1
  88. package/src/{pr-intake-mode.ts → pr/pr-intake-mode.ts} +3 -3
  89. package/src/{pr-intake-review.ts → pr/pr-intake-review.ts} +5 -5
  90. package/src/{pr-intake-work.ts → pr/pr-intake-work.ts} +1 -1
  91. package/src/{pr-review-models.ts → pr/pr-review-models.ts} +2 -2
  92. package/src/{pr-watch.ts → pr/pr-watch.ts} +36 -26
  93. package/src/{message-order.ts → routing/message-order.ts} +1 -1
  94. package/src/{topic-history.ts → routing/topic-history.ts} +2 -2
  95. package/src/{topic-request.ts → routing/topic-request.ts} +4 -2
  96. package/src/{runtime.ts → runtime/controller.ts} +867 -1213
  97. package/src/runtime/deferred-routing.ts +106 -0
  98. package/src/runtime/dm-timeline.ts +194 -0
  99. package/src/{head-recovery.ts → runtime/head-recovery.ts} +1 -1
  100. package/src/{head-rotation.ts → runtime/head-rotation.ts} +32 -5
  101. package/src/runtime/model-journal.ts +119 -0
  102. package/src/runtime/native-frames.ts +131 -0
  103. package/src/{observation-request.ts → runtime/observation-request.ts} +1 -1
  104. package/src/runtime/preset-sync.ts +232 -0
  105. package/src/runtime/preset-watch-paths.ts +137 -0
  106. package/src/runtime/result-attachments.ts +146 -0
  107. package/src/storage/deferred-routing.ts +149 -0
  108. package/src/{store.ts → storage/store.ts} +75 -42
  109. package/src/{worker-bridge.ts → worker/worker-bridge.ts} +2 -2
  110. package/src/{worker-enrollment.ts → worker/worker-enrollment.ts} +2 -2
  111. package/src/{worker-host.ts → worker/worker-host.ts} +7 -3
  112. package/src/{worker-placement.ts → worker/worker-placement.ts} +1 -1
  113. package/src/{worker-profile.ts → worker/worker-profile.ts} +1 -1
  114. package/src/{worker-registration.ts → worker/worker-registration.ts} +2 -2
  115. package/src/{worker-request.ts → worker/worker-request.ts} +5 -5
  116. package/src/{worker-service.ts → worker/worker-service.ts} +2 -2
  117. package/src/{worker-trust.ts → worker/worker-trust.ts} +1 -1
  118. package/src/{worker-wire.ts → worker/worker-wire.ts} +3 -3
  119. package/src/worker-serve-prepare.ts +4 -4
  120. package/src/board-extension.ts +0 -217
  121. package/src/board.ts +0 -467
  122. package/src/gateway-host-helper.ts +0 -13
  123. package/src/messenger-commands.ts +0 -15
  124. package/src/native-sessions.ts +0 -34
  125. /package/src/{credentials.ts → config/credentials.ts} +0 -0
  126. /package/src/{lane-report.ts → lane/lane-report.ts} +0 -0
  127. /package/src/{dialog.ts → messaging/dialog.ts} +0 -0
  128. /package/src/{telegram-command-languages.json → messaging/telegram-command-languages.json} +0 -0
  129. /package/src/{host-broker-services.ts → omp/host-broker-services.ts} +0 -0
  130. /package/src/{host-inventory-manifest.ts → omp/host-inventory-manifest.ts} +0 -0
  131. /package/src/{host-reply-voice.ts → omp/host-reply-voice.ts} +0 -0
  132. /package/src/{host-services.ts → omp/host-services.ts} +0 -0
  133. /package/src/{native-settings.ts → omp/native-settings.ts} +0 -0
  134. /package/src/{superkit-skills.ts → omp/superkit-skills.ts} +0 -0
  135. /package/src/{repository.ts → operator/repository.ts} +0 -0
  136. /package/src/{pr-github-schema.ts → pr/pr-github-schema.ts} +0 -0
  137. /package/src/{pr-github.ts → pr/pr-github.ts} +0 -0
  138. /package/src/{pr-intake-comment.ts → pr/pr-intake-comment.ts} +0 -0
  139. /package/src/{pr-intake-fix.ts → pr/pr-intake-fix.ts} +0 -0
  140. /package/src/{pr-intake-github.ts → pr/pr-intake-github.ts} +0 -0
  141. /package/src/{pr-intake-material.ts → pr/pr-intake-material.ts} +0 -0
  142. /package/src/{pr-intake-tree.ts → pr/pr-intake-tree.ts} +0 -0
  143. /package/src/{head-quota.ts → runtime/head-quota.ts} +0 -0
  144. /package/src/{worker-checkout.ts → worker/worker-checkout.ts} +0 -0
  145. /package/src/{worker-destination.ts → worker/worker-destination.ts} +0 -0
  146. /package/src/{worker-doctor.ts → worker/worker-doctor.ts} +0 -0
  147. /package/src/{worker-ledger.ts → worker/worker-ledger.ts} +0 -0
  148. /package/src/{worker-repository.ts → worker/worker-repository.ts} +0 -0
  149. /package/upstream/{ulw.json → super.json} +0 -0
package/src/extension.ts CHANGED
@@ -4,23 +4,25 @@ 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
6
  import { Type } from "@sinclair/typebox";
7
- import { configuredPlatforms, hostPaths, loadConfigSnapshot } from "./config";
8
- import { createGatewayMessenger } from "./gateway-client";
9
- import { Superagent } from "./runtime";
10
- import { Store } from "./store";
11
- import { lanePlacement } from "./lane-rows";
12
- import { sameLaneModel } from "./lane-models";
13
- import { NativePresetManager } from "./native-presets";
14
- import { publishNativeSession } from "./native-sessions";
15
- import { isPrReviewLane } from "./pr-intake-review";
7
+ import { configuredPlatforms, hostPaths, loadConfigSnapshot } from "./config/config";
8
+ import { loadWakeConfig } from "./config/wake-config";
9
+ import { createGatewayMessenger } from "./gateway/gateway-client";
10
+ import { Superagent } from "./runtime/controller";
11
+ import { Store } from "./storage/store";
12
+ import { lanePlacement } from "./lane/lane-rows";
13
+ import { sameLaneModel } from "./lane/lane-models";
14
+ import { NativePresetManager } from "./omp/native-presets";
15
+ import { publishNativeSession, type HostReadyEvent } from "./omp/native-sessions";
16
+ import { isPrReviewLane } from "./pr/pr-intake-review";
16
17
  import { MODEL_PRESET_NAMES, WORKFLOW_NAMES } from "./contracts";
17
- import type { PrWatchCommand } from "./pr-watch";
18
- import type { LaneWatchCommand } from "./lane-watch";
19
- import { registerDecisionAsk } from "./decision-tool";
20
- import { registerResultAttach, RESULT_ATTACH_TOOL } from "./result-attachment";
21
- import { HEAD_ROTATION_GUARD, HEAD_ROTATION_PROBE, type RotationGuardEvent, type RotationProbeEvent } from "./head-rotation";
22
- import { readHeadQuota } from "./head-quota";
23
- import { soulUpdateSchema } from "./soul";
18
+ import type { PrWatchCommand } from "./pr/pr-watch";
19
+ import type { LaneWatchCommand } from "./lane/lane-watch";
20
+ import { registerDecisionAsk } from "./lane/decision-tool";
21
+ import { registerResultAttach, RESULT_ATTACH_TOOL } from "./messaging/result-attachment";
22
+ import { HEAD_ROTATION_GUARD, HEAD_ROTATION_PROBE, HEAD_SLEEP_PROBE_READY, type HeadSleepProbeReadyEvent,
23
+ type RotationGuardEvent, type RotationProbeEvent } from "./runtime/head-rotation";
24
+ import { readHeadQuota } from "./runtime/head-quota";
25
+ import { soulUpdateSchema } from "./omp/soul";
24
26
 
25
27
  // Inject the role contract, not the references. Resolve the reference directory
26
28
  // from this package so a same-name workspace skill cannot change the procedure.
@@ -62,17 +64,22 @@ export default function superagentExtension(pi: ExtensionAPI): void {
62
64
  // Subagents inherit environment but must not acquire the head's controller.
63
65
  let runtime: Superagent | undefined;
64
66
  let loading: Promise<void> | undefined;
67
+ const hostShutdown = new AbortController();
65
68
  let closed = false;
66
69
  let startupError: unknown;
67
70
  let timer: ReturnType<typeof setTimeout> | undefined;
68
71
  let stopHostReady: (() => void) | undefined;
72
+ const stopSleepProbeReady = pi.events.on(HEAD_SLEEP_PROBE_READY, value => {
73
+ const { respond } = value as HeadSleepProbeReadyEvent;
74
+ respond(runtime?.canProbeHeadSleep() ?? false);
75
+ });
69
76
  const stopRotationProbe = pi.events.on(HEAD_ROTATION_PROBE, value => {
70
- const { state, respond } = value as RotationProbeEvent;
71
- respond(runtime?.attestHeadRotation(state) ?? Promise.resolve(null));
77
+ const { mode, state, respond } = value as RotationProbeEvent;
78
+ respond(runtime?.attestHeadRotation(state, mode) ?? Promise.resolve(null));
72
79
  });
73
80
  const stopRotationGuard = pi.events.on(HEAD_ROTATION_GUARD, value => {
74
- const { id, state, respond } = value as RotationGuardEvent;
75
- respond(runtime?.guardHeadRotation(id, state) ?? false);
81
+ const { id, mode, state, respond } = value as RotationGuardEvent;
82
+ respond(runtime?.guardHeadRotation(id, state, mode) ?? false);
76
83
  });
77
84
  let presets: Promise<NativePresetManager> | undefined;
78
85
  const requireRuntime = (ctx: ExtensionContext) => {
@@ -126,6 +133,8 @@ export default function superagentExtension(pi: ExtensionAPI): void {
126
133
  if (scoped.length !== active.length) await pi.setActiveTools(scoped);
127
134
  });
128
135
  pi.on("tool_call", (event, ctx) => {
136
+ if (runtime?.laneDecisionReviewActive() && (ctx.agent.kind !== "main" || event.toolName !== "lane_review_decision"))
137
+ return { block: true, reason: "A lane question permits only answering or escalating its original decision" };
129
138
  if (runtime?.scopeReviewActive() && (ctx.agent.kind !== "main" || event.toolName !== "lane_message"))
130
139
  return { block: true, reason: "This assignment review permits only a direct same-lane correction from its verified owner message" };
131
140
  if (event.toolName === "soul_update") {
@@ -513,14 +522,20 @@ export default function superagentExtension(pi: ExtensionAPI): void {
513
522
  throw new Error("Start this extension with omp-sa start and its owned stock OMP host");
514
523
  // Native startup precedes the private pipe owner's socket readiness.
515
524
  // Activate only after that exact owner has materialized and verified us.
516
- stopHostReady = pi.events.on("superagent:host-ready", () => {
525
+ stopHostReady = pi.events.on("superagent:host-ready", value => {
517
526
  if (timer || loading || closed) return;
518
527
  timer = setTimeout(() => {
519
528
  loading = (async () => {
520
- const { config, sourceHash } = await loadConfigSnapshot(configPath);
529
+ const { nativeProfile, waking } = value as HostReadyEvent;
530
+ if (!nativeProfile) throw new Error("HEAD did not identify its native session storage");
521
531
  const restartHash = process.env.OMP_SUPERAGENT_RESTART_CONFIG_SHA256;
522
- if (restartHash !== undefined && restartHash !== sourceHash)
532
+ if (waking && !restartHash) throw new Error("HEAD wake is missing its reserved configuration");
533
+ const snapshot = waking && restartHash
534
+ ? { config: await loadWakeConfig(configPath, restartHash, hostShutdown.signal), sourceHash: restartHash }
535
+ : await loadConfigSnapshot(configPath);
536
+ if (restartHash !== undefined && restartHash !== snapshot.sourceHash)
523
537
  throw new Error("Gateway configuration changed before replacement HEAD initialization");
538
+ const { config } = snapshot;
524
539
  delete process.env.OMP_SUPERAGENT_RESTART_CONFIG_SHA256;
525
540
  const store = new Store(join(config.stateDir, "coordination.sqlite"));
526
541
  let messenger: ReturnType<typeof createGatewayMessenger>;
@@ -529,9 +544,9 @@ export default function superagentExtension(pi: ExtensionAPI): void {
529
544
  if (lane.remote || !lane.sessionId || isPrReviewLane(store, lane.id)) continue;
530
545
  const { sessionFile } = hostPaths(config, lane.id);
531
546
  if (lane.sessionFile !== sessionFile) throw new Error("Refusing to publish a lane outside its managed session path");
532
- await publishNativeSession(sessionFile, lane.cwd, lane.sessionId);
547
+ await publishNativeSession(sessionFile, lane.cwd, lane.sessionId, nativeProfile);
533
548
  }
534
- messenger = createGatewayMessenger(config);
549
+ messenger = createGatewayMessenger(config, hostShutdown.signal);
535
550
  } catch (error) {
536
551
  store.close();
537
552
  throw error;
@@ -579,6 +594,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
579
594
  throw error;
580
595
  }
581
596
  })().catch(error => {
597
+ if (closed) return;
582
598
  startupError = error;
583
599
  pi.logger.error(`Superagent startup failed: ${error instanceof Error ? error.message : String(error)}`);
584
600
  ctx.ui.setStatus("superagent", "startup failed; see host log");
@@ -588,9 +604,11 @@ export default function superagentExtension(pi: ExtensionAPI): void {
588
604
  });
589
605
  pi.on("session_shutdown", async () => {
590
606
  closed = true;
607
+ hostShutdown.abort();
591
608
  stopHostReady?.();
592
609
  stopRotationProbe();
593
610
  stopRotationGuard();
611
+ stopSleepProbeReady();
594
612
  if (timer) clearTimeout(timer);
595
613
  await loading;
596
614
  await runtime?.stop();
@@ -1,35 +1,54 @@
1
1
  import type { IncomingMessage } from "node:http";
2
- import type { Config } from "./config";
2
+ import { setTimeout as delay } from "node:timers/promises";
3
+ import type { Config } from "../config/config";
3
4
  import { createHash } from "node:crypto";
4
- import type { Approval, DiscordContext, DiscordPurposeNote, DiscordPurposeRequest, GatewayRestartRecord, GatewayRestartRequest, Inbound, InboundAttachmentBatch, InboundAttachmentReceipt, MessageActivity, MessageReference, Messenger, OutputRecord, Route, ThreadInfo, ThreadUpdate } from "./contracts";
5
- import { DeliveryError } from "./delivery";
6
- import { gatewayCall, gatewayPaths, gatewayRequest, MAX_GATEWAY_FRAME, parseInboundAttachmentReceipt, readGatewayJson, type GatewayResult } from "./gateway-protocol";
5
+ import type { Approval, DiscordContext, DiscordPurposeNote, DiscordPurposeRequest, GatewayRestartRecord, GatewayRestartRequest, Inbound, InboundAttachmentBatch, InboundAttachmentReceipt, MessageActivity, MessageReference, Messenger, OutputRecord, Route, ThreadInfo, ThreadUpdate } from "../contracts";
6
+ import { DeliveryError } from "../messaging/delivery";
7
+ import {
8
+ gatewayCall, gatewayPaths, GatewaySocketChangedError, MAX_GATEWAY_FRAME, openGatewayEvents, parseInboundAttachmentReceipt,
9
+ type GatewayEventConnection, type GatewaySocketIdentity,
10
+ } from "./gateway-protocol";
7
11
  import type { GatewayReceipt, QueuedEvent } from "./gateway-wire";
8
- import type { GroupReply } from "./group-policy";
9
- import type { DiscordPresenceStatus, MessengerPresenceRequest } from "./contracts";
12
+ import type { GroupReply } from "../group/group-policy";
13
+ import type { DiscordPresenceStatus, MessengerPresenceRequest } from "../contracts";
10
14
 
11
15
  export interface GatewayHeadMessenger extends Messenger {
12
16
  assertRoute(route: Route, purpose?: "history"): Promise<void>;
13
17
  requestRestart(request: GatewayRestartRequest): Promise<GatewayRestartRecord>;
14
18
  }
15
19
 
20
+ function retryableHandshake(error: unknown): boolean {
21
+ if (error instanceof GatewaySocketChangedError) return true;
22
+ const cause = error instanceof DeliveryError ? error.cause : error;
23
+ return cause instanceof Error && "code" in cause
24
+ && ["ENOENT", "ECONNREFUSED", "ECONNRESET", "EPIPE"].includes(String(cause.code));
25
+ }
26
+
27
+ function retryableReconnect(error: unknown): boolean {
28
+ return retryableHandshake(error) || (error instanceof DeliveryError && error.certainty === "uncertain");
29
+ }
30
+
16
31
  /** Transport-only head adapter. Detaching never logs out the actual accounts. */
17
32
  class GatewayMessenger implements GatewayHeadMessenger {
33
+ readonly managesStartupHistory = true;
18
34
  private readonly clientId = crypto.randomUUID();
19
35
  private readonly socketPath: string;
20
36
  private readonly token: string;
21
37
  private handlers?: Parameters<Messenger["start"]>[0];
22
- private events?: IncomingMessage;
38
+ private events?: GatewayEventConnection;
23
39
  private stopped = false;
24
40
  private reconnectTimer?: ReturnType<typeof setTimeout>;
25
41
  private delivery: Promise<void> = Promise.resolve();
26
42
  private intakeReady = false;
27
43
  private connecting?: Promise<void>;
28
44
  private reconnectDelay = 250;
45
+ private readonly detach = new AbortController();
46
+ private readonly startupSignal: AbortSignal;
29
47
 
30
- constructor(config: Config) {
48
+ constructor(config: Config, hostShutdown?: AbortSignal) {
31
49
  this.socketPath = gatewayPaths(config).socketPath;
32
50
  this.token = process.env.OMP_SUPERAGENT_GATEWAY_TOKEN ?? "";
51
+ this.startupSignal = hostShutdown ? AbortSignal.any([hostShutdown, this.detach.signal]) : this.detach.signal;
33
52
  }
34
53
 
35
54
  private options() { return { token: this.token, clientId: this.clientId }; }
@@ -38,51 +57,81 @@ class GatewayMessenger implements GatewayHeadMessenger {
38
57
  return gatewayCall<T>(this.socketPath, endpoint, body, { ...this.options(), signal });
39
58
  }
40
59
 
60
+ private markReady(expectedSocket: GatewaySocketIdentity): Promise<void> {
61
+ return gatewayCall(this.socketPath, "/ready", {}, { ...this.options(), expectedSocket, signal: this.detach.signal });
62
+ }
63
+
41
64
  async start(handlers: Parameters<Messenger["start"]>[0]): Promise<void> {
42
65
  if (this.handlers || this.stopped) throw new Error("Gateway messenger cannot be started twice");
43
66
  if (!this.token) throw new DeliveryError("Head was not launched by its Gateway", "rejected");
44
67
  this.handlers = handlers;
45
68
  try {
46
- await this.connect();
69
+ // A reserved Host can become ready while its Gateway is being replaced.
70
+ // Repeat only the authenticated handshake, never a handler or an effect.
71
+ for (;;) {
72
+ this.startupSignal.throwIfAborted();
73
+ try { await this.connect(this.startupSignal); break; }
74
+ catch (error) {
75
+ if (!retryableHandshake(error)) throw error;
76
+ await delay(this.reconnectDelay, undefined, { signal: this.startupSignal, ref: false });
77
+ }
78
+ }
79
+ this.startupSignal.throwIfAborted();
47
80
  // Return before the native-approval gate, like the actual adapters. The
48
81
  // head must attach/reconcile native UI before enabling any admission.
49
82
  void (handlers.ready ?? Promise.resolve()).then(async () => {
50
83
  if (this.stopped) return;
51
84
  this.intakeReady = true;
52
- await this.call("/ready", {});
53
- }).catch(() => { this.events?.destroy(); });
85
+ const events = this.events;
86
+ // If the stream already disconnected, its replacement will send ready.
87
+ if (!events) return;
88
+ try { await this.markReady(events.socket); }
89
+ catch (error) {
90
+ if (this.events !== events) return;
91
+ this.events = undefined;
92
+ events.stream.destroy();
93
+ if (retryableReconnect(error)) this.scheduleReconnect();
94
+ }
95
+ }, () => { this.events?.stream.destroy(); });
54
96
  } catch (error) {
55
97
  await this.stop();
56
98
  throw error;
57
99
  }
58
100
  }
59
101
 
60
- private connect(): Promise<void> {
102
+ private connect(signal?: AbortSignal): Promise<void> {
61
103
  if (this.connecting) return this.connecting;
62
- this.connecting = this.openEvents().finally(() => { this.connecting = undefined; });
104
+ this.connecting = this.openEvents(signal).finally(() => { this.connecting = undefined; });
63
105
  return this.connecting;
64
106
  }
65
- private async openEvents(): Promise<void> {
66
- await this.call("/attach", { pid: process.pid, resumed: this.intakeReady });
67
- const events = await gatewayRequest(this.socketPath, "/events", undefined, this.options());
68
- if (events.statusCode !== 200) {
69
- const result = await readGatewayJson(events) as GatewayResult;
70
- throw new DeliveryError(result.error ?? "Gateway event stream rejected", result.certainty ?? "rejected");
107
+ private async openEvents(signal = this.detach.signal): Promise<void> {
108
+ const connection = await openGatewayEvents(this.socketPath, {
109
+ ...this.options(), pid: process.pid, resumed: this.intakeReady,
110
+ startupHistory: this.handlers?.reserveStartupHistory !== undefined, signal,
111
+ });
112
+ try {
113
+ signal.throwIfAborted();
114
+ if (this.intakeReady) await this.markReady(connection.socket);
115
+ signal.throwIfAborted();
116
+ if (connection.reserveHistory) this.handlers?.reserveStartupHistory?.();
117
+ } catch (error) {
118
+ connection.stream.destroy();
119
+ throw error;
71
120
  }
72
- if (this.stopped) { events.destroy(); return; }
73
- this.events = events;
74
- void this.consume(events).catch(() => { events.destroy(); }).finally(() => {
75
- if (this.events !== events) return;
121
+ this.events = connection;
122
+ void this.consume(connection.stream).catch(() => { connection.stream.destroy(); }).finally(() => {
123
+ if (this.events !== connection) return;
76
124
  this.events = undefined;
77
125
  this.scheduleReconnect();
78
126
  });
79
- if (this.intakeReady) await this.call("/ready", {});
80
127
  }
81
128
  private scheduleReconnect(): void {
82
129
  if (this.stopped || this.reconnectTimer) return;
83
130
  this.reconnectTimer = setTimeout(() => {
84
131
  this.reconnectTimer = undefined;
85
- void this.connect().catch(() => { this.scheduleReconnect(); });
132
+ void this.connect().catch(error => {
133
+ if (retryableReconnect(error)) this.scheduleReconnect();
134
+ });
86
135
  }, this.reconnectDelay);
87
136
  this.reconnectTimer.unref();
88
137
  }
@@ -104,6 +153,7 @@ class GatewayMessenger implements GatewayHeadMessenger {
104
153
  if (this.stopped || !this.handlers) return;
105
154
  disconnected.signal.throwIfAborted();
106
155
  let outcome: GatewayReceipt = "accepted";
156
+ let retryAfterMs = 0;
107
157
  try {
108
158
  const event = frame.event;
109
159
  if (event.kind === "message") await this.handlers.message(event.input);
@@ -122,16 +172,18 @@ class GatewayMessenger implements GatewayHeadMessenger {
122
172
  const { kind: _, ...notice } = event;
123
173
  await this.handlers.restart(notice);
124
174
  }
125
- else await this.handlers.reconnect?.();
175
+ else await this.handlers.reconnect?.(event.historyRecovery === true ? frame.sequence : false, event.historyPlatform);
126
176
  } catch (error) {
127
177
  outcome = error instanceof DeliveryError && error.certainty === "rejected" ? "rejected" : "unresolved";
178
+ const retryHint = error instanceof DeliveryError ? error.retryAfterMs : undefined;
179
+ if (outcome === "unresolved" && retryHint !== undefined && Number.isFinite(retryHint)) retryAfterMs = retryHint;
128
180
  }
129
181
  // A handler may finish after its Gateway has been replaced. Its
130
182
  // receipt belongs only to this stream; redelivery reconciles the
131
183
  // durable outcome after reattachment instead of ACKing a new server.
132
184
  disconnected.signal.throwIfAborted();
133
185
  // A poison input stays visible and ordered without a tight retry loop.
134
- this.reconnectDelay = outcome === "unresolved" ? Math.min(this.reconnectDelay * 2, 30_000) : 250;
186
+ this.reconnectDelay = outcome === "unresolved" ? Math.max(retryAfterMs, Math.min(this.reconnectDelay * 2, 30_000)) : 250;
135
187
  await this.call("/receipt", { sequence: frame.sequence, outcome }, disconnected.signal);
136
188
  });
137
189
  await this.delivery;
@@ -185,7 +237,9 @@ class GatewayMessenger implements GatewayHeadMessenger {
185
237
  return this.effect("messengerPresence", [request]);
186
238
  }
187
239
  discordPurpose(request: DiscordPurposeRequest): Promise<readonly DiscordPurposeNote[]> { return this.effect("discordPurpose", [request]); }
188
- fetchAfter(route: Route, messageId: string): Promise<Inbound[] | null> { return this.effect("fetchAfter", [route, messageId]); }
240
+ fetchAfter(route: Route, messageId: string, historySequence?: number): Promise<Inbound[] | null> {
241
+ return this.effect("fetchAfter", historySequence === undefined ? [route, messageId] : [route, messageId, historySequence]);
242
+ }
189
243
 
190
244
  async openAttachment(batch: InboundAttachmentBatch, signal: AbortSignal): Promise<InboundAttachmentReceipt> {
191
245
  if (this.stopped) throw new DeliveryError("Gateway client is stopped", "rejected");
@@ -197,14 +251,17 @@ class GatewayMessenger implements GatewayHeadMessenger {
197
251
 
198
252
  async stop(): Promise<void> {
199
253
  if (this.stopped) return;
200
- // Detach is best effort, never a messenger/server shutdown request.
201
- try { await this.call("/detach", {}); } catch { /* Gateway may be unavailable. */ }
202
254
  this.stopped = true;
255
+ this.detach.abort();
203
256
  if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
204
- this.events?.destroy();
257
+ this.events?.stream.destroy();
205
258
  this.events = undefined;
206
259
  this.handlers = undefined;
260
+ // Detach is best effort, never a messenger/server shutdown request.
261
+ try { await gatewayCall(this.socketPath, "/detach", {}, this.options()); } catch { /* Gateway may be unavailable. */ }
207
262
  }
208
263
  }
209
264
 
210
- export function createGatewayMessenger(config: Config): GatewayHeadMessenger { return new GatewayMessenger(config); }
265
+ export function createGatewayMessenger(config: Config, hostShutdown?: AbortSignal): GatewayHeadMessenger {
266
+ return new GatewayMessenger(config, hostShutdown);
267
+ }
@@ -3,12 +3,12 @@ import { constants } from "node:fs";
3
3
  import { access } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
- import type { Config } from "./config";
7
- import type { GatewayRestartRecord } from "./contracts";
8
- import { DeliveryError } from "./delivery";
6
+ import type { Config } from "../config/config";
7
+ import type { GatewayRestartRecord } from "../contracts";
8
+ import { DeliveryError } from "../messaging/delivery";
9
9
  import { gatewayCall, gatewayPaths, gatewayStatus } from "./gateway-protocol";
10
10
 
11
- const root = fileURLToPath(new URL("../", import.meta.url));
11
+ const root = fileURLToPath(new URL("../../", import.meta.url));
12
12
  const binary = join(root, "gateway", "bin", `omp-gateway-${process.platform}-${process.arch}`);
13
13
 
14
14
  export async function requireGateway(): Promise<string> {
@@ -3,15 +3,27 @@ import { request, type IncomingMessage } from "node:http";
3
3
  import { existsSync } from "node:fs";
4
4
  import { lstat, realpath } from "node:fs/promises";
5
5
  import { dirname, join } from "node:path";
6
- import type { Config } from "./config";
7
- import type { InboundAttachmentBatch, InboundAttachmentReceipt } from "./contracts";
8
- import { DeliveryError } from "./delivery";
6
+ import type { Config } from "../config/config";
7
+ import type { InboundAttachmentBatch, InboundAttachmentReceipt } from "../contracts";
8
+ import { DeliveryError } from "../messaging/delivery";
9
9
  import type { GatewayStatus } from "./gateway-wire";
10
10
 
11
11
  export const MAX_GATEWAY_FRAME = 16 * 1024 * 1024;
12
12
  export const MAX_GATEWAY_ATTACHMENT = 20 * 1024 * 1024;
13
13
  export const MAX_GATEWAY_ATTACHMENT_BATCH = 40 * 1024 * 1024;
14
14
  export interface GatewayResult { ok: boolean; value?: unknown; error?: string; certainty?: "rejected" | "uncertain"; retryAfterMs?: number }
15
+ export type GatewaySocketIdentity = { readonly dev: number; readonly ino: number };
16
+ export type GatewayEventConnection = {
17
+ readonly stream: IncomingMessage;
18
+ readonly socket: GatewaySocketIdentity;
19
+ readonly reserveHistory: boolean;
20
+ };
21
+
22
+ export class GatewaySocketChangedError extends DeliveryError {
23
+ constructor(certainty: "rejected" | "uncertain") {
24
+ super("Gateway socket changed during request", certainty);
25
+ }
26
+ }
15
27
 
16
28
  export function gatewayPaths(config: Pick<Config, "stateDir">) {
17
29
  const socketPath = join(config.stateDir, "run", "gateway.sock");
@@ -25,7 +37,7 @@ export async function gatewayStatus(config: Config): Promise<GatewayStatus | nul
25
37
  return gatewayCall<GatewayStatus>(path, "/status");
26
38
  }
27
39
 
28
- export async function trustedGatewaySocket(socketPath: string): Promise<{ dev: number; ino: number }> {
40
+ export async function trustedGatewaySocket(socketPath: string): Promise<GatewaySocketIdentity> {
29
41
  const directory = await lstat(dirname(socketPath));
30
42
  const stat = await lstat(socketPath);
31
43
  if (!directory.isDirectory() || directory.isSymbolicLink() || directory.uid !== process.getuid?.() ||
@@ -34,6 +46,17 @@ export async function trustedGatewaySocket(socketPath: string): Promise<{ dev: n
34
46
  return { dev: stat.dev, ino: stat.ino };
35
47
  }
36
48
 
49
+ function requireSameSocket(expected: GatewaySocketIdentity, actual: GatewaySocketIdentity, certainty: "rejected" | "uncertain"): void {
50
+ if (expected.dev !== actual.dev || expected.ino !== actual.ino) throw new GatewaySocketChangedError(certainty);
51
+ }
52
+
53
+ async function verifyResponseSocket(socketPath: string, expected: GatewaySocketIdentity): Promise<void> {
54
+ const actual = await trustedGatewaySocket(socketPath).catch(cause => {
55
+ throw new DeliveryError("Gateway socket could not be verified after request", "uncertain", undefined, { cause });
56
+ });
57
+ requireSameSocket(expected, actual, "uncertain");
58
+ }
59
+
37
60
  export async function readGatewayJson(stream: IncomingMessage): Promise<unknown> {
38
61
  let bytes = 0;
39
62
  const chunks: Buffer[] = [];
@@ -48,32 +71,32 @@ export async function readGatewayJson(stream: IncomingMessage): Promise<unknown>
48
71
 
49
72
  /** One attempt only. A lost response is never converted to a known rejection. */
50
73
  export async function gatewayRequest(socketPath: string, endpoint: string, body?: unknown, options: {
51
- token?: string; clientId?: string; signal?: AbortSignal; timeoutMs?: number;
74
+ token?: string; clientId?: string; signal?: AbortSignal; timeoutMs?: number; expectedSocket?: GatewaySocketIdentity;
52
75
  } = {}): Promise<IncomingMessage> {
53
76
  const before = await trustedGatewaySocket(socketPath);
77
+ if (options.expectedSocket) requireSameSocket(options.expectedSocket, before, "rejected");
54
78
  const data = body === undefined ? undefined : Buffer.from(JSON.stringify(body));
55
79
  if (data && data.length > MAX_GATEWAY_FRAME) throw new DeliveryError("Gateway frame exceeds size limit", "rejected");
56
80
  const { promise, resolve, reject } = Promise.withResolvers<IncomingMessage>();
57
81
  let answered = false;
58
82
  const req = request({ socketPath, path: endpoint, method: body === undefined ? "GET" : "POST",
83
+ ...(options.expectedSocket ? { agent: false } : {}),
59
84
  headers: { ...(data ? { "content-type": "application/json", "content-length": data.length } : {}),
60
85
  ...(options.token ? { authorization: `Bearer ${options.token}` } : {}),
61
86
  ...(options.clientId ? { "x-gateway-client": options.clientId } : {}) }, signal: options.signal,
62
87
  }, response => {
63
88
  answered = true;
64
89
  clearTimeout(timer);
65
- void trustedGatewaySocket(socketPath).then(after => {
66
- if (before.dev !== after.dev || before.ino !== after.ino) {
67
- response.destroy();
68
- reject(new DeliveryError("Gateway socket changed during request", "uncertain"));
69
- } else resolve(response);
70
- }, error => { response.destroy(); reject(error); });
90
+ void verifyResponseSocket(socketPath, before).then(
91
+ () => resolve(response),
92
+ error => { response.destroy(); reject(error); },
93
+ );
71
94
  });
72
95
  const timer = setTimeout(() => req.destroy(new Error("Gateway request timed out")), options.timeoutMs ?? 30_000);
73
96
  timer.unref();
74
- req.on("error", () => {
97
+ req.on("error", cause => {
75
98
  clearTimeout(timer);
76
- if (!answered) reject(new DeliveryError("Gateway request outcome uncertain", "uncertain"));
99
+ if (!answered) reject(new DeliveryError("Gateway request outcome uncertain", "uncertain", undefined, { cause }));
77
100
  });
78
101
  if (data) req.write(data);
79
102
  req.end();
@@ -82,11 +105,43 @@ export async function gatewayRequest(socketPath: string, endpoint: string, body?
82
105
 
83
106
  export async function gatewayCall<T>(socketPath: string, endpoint: string, body?: unknown, options?: Parameters<typeof gatewayRequest>[3]): Promise<T> {
84
107
  const response = await gatewayRequest(socketPath, endpoint, body, options);
85
- const result = await readGatewayJson(response) as GatewayResult;
108
+ const expected = options?.expectedSocket;
109
+ const json = readGatewayJson(response);
110
+ const result = await (expected ? json.finally(() => verifyResponseSocket(socketPath, expected)) : json) as GatewayResult;
86
111
  if (!result.ok) throw new DeliveryError(result.error ?? "Gateway rejected operation", result.certainty ?? "uncertain", result.retryAfterMs);
87
112
  return result.value as T;
88
113
  }
89
114
 
115
+ /** An attachment and its event stream must authorize on the same verified inode. */
116
+ export async function openGatewayEvents(socketPath: string, attach: {
117
+ readonly token: string; readonly clientId: string; readonly pid: number; readonly resumed: boolean;
118
+ readonly startupHistory: boolean; readonly signal: AbortSignal;
119
+ }): Promise<GatewayEventConnection> {
120
+ const { pid, resumed, startupHistory, signal, ...auth } = attach;
121
+ const socket = await trustedGatewaySocket(socketPath);
122
+ const options = { ...auth, expectedSocket: socket };
123
+ const attachment = await gatewayCall<unknown>(socketPath, "/attach", {
124
+ pid, resumed, ...(startupHistory ? { startupHistory } : {}),
125
+ }, { ...options, signal });
126
+ let reserveHistory = false;
127
+ if (startupHistory) {
128
+ if (!attachment || typeof attachment !== "object" || !("admissionReady" in attachment)
129
+ || typeof attachment.admissionReady !== "boolean")
130
+ throw new DeliveryError("Gateway does not support ordered startup history. Restart Gateway and HEAD together using the same installation.", "rejected");
131
+ reserveHistory = !attachment.admissionReady;
132
+ }
133
+ // The delivery stream outlives startup; its owner destroys it at detach.
134
+ signal.throwIfAborted();
135
+ const stream = await gatewayRequest(socketPath, "/events", undefined, options);
136
+ if (stream.statusCode !== 200) {
137
+ try {
138
+ const result = await readGatewayJson(stream).finally(() => verifyResponseSocket(socketPath, socket)) as GatewayResult;
139
+ throw new DeliveryError(result.error ?? "Gateway event stream rejected", result.certainty ?? "rejected");
140
+ } finally { stream.destroy(); }
141
+ }
142
+ return { stream, socket, reserveHistory };
143
+ }
144
+
90
145
  /** A spool reply carries only correctly indexed local references, never attachment bytes. */
91
146
  export async function parseInboundAttachmentReceipt(
92
147
  socketPath: string, batch: InboundAttachmentBatch, value: unknown,
@@ -1,7 +1,7 @@
1
- import type { DialogResponse, GatewayRestartNotice, GatewayRestartRecord, Inbound, Route } from "./contracts";
2
- import type { HeadRotation } from "./head-rotation";
3
- import type { ManagedUlwStatus } from "./managed-ulw";
4
- import type { GroupRequest } from "./group-policy";
1
+ import type { DialogResponse, GatewayRestartNotice, GatewayRestartRecord, HistoryPlatform, Inbound, Route } from "../contracts";
2
+ import type { HeadRotation } from "../runtime/head-rotation";
3
+ import type { ManagedUlwStatus } from "../omp/managed-super";
4
+ import type { GroupRequest } from "../group/group-policy";
5
5
 
6
6
  export type HeadInitialization = {
7
7
  readonly sessionId: string;
@@ -30,20 +30,25 @@ export type GatewayStatus = {
30
30
  readonly socketPath: string;
31
31
  readonly error: string | null;
32
32
  readonly initialization?: HeadInitialization;
33
- readonly rotation?: Pick<HeadRotation, "id" | "stage" | "replacementSessionId"> & {
33
+ readonly rotation?: Pick<HeadRotation, "id" | "replacementSessionId"> & {
34
+ readonly stage: Exclude<HeadRotation["stage"], "sleeping">;
34
35
  readonly previousSessionId: string;
35
36
  };
37
+ readonly hibernation?: Pick<HeadRotation, "id" | "stage"> & {
38
+ readonly sessionId: string;
39
+ };
36
40
  };
37
41
  readonly ulw?: ManagedUlwStatus;
38
42
  readonly restart?: Omit<GatewayRestartRecord, "sessionFile">;
39
43
  };
40
44
 
41
45
  export type GatewayEvent =
42
- | { readonly kind: "message"; readonly input: Inbound }
46
+ | { readonly kind: "message"; readonly input: Inbound; readonly historyDeferred?: true }
43
47
  | { readonly kind: "group"; readonly request: GroupRequest }
44
48
  | { readonly kind: "answer"; readonly approvalId: string; readonly response: DialogResponse; readonly route: Route }
45
49
  | ({ readonly kind: "restart" } & GatewayRestartNotice)
46
- | { readonly kind: "reconnect"; readonly barrier?: string };
50
+ | { readonly kind: "reconnect"; readonly barrier?: string; readonly historyRecovery?: true;
51
+ readonly historyPlatform?: HistoryPlatform; readonly historyBeforeUs?: number };
47
52
  export type GatewayReceipt = "accepted" | "rejected" | "unresolved";
48
53
  export type QueuedEvent = {
49
54
  readonly sequence: number;
@@ -1,6 +1,6 @@
1
1
  // One-shot parser shared with the operator CLI. Return normalized config and
2
2
  // its source digest; never load credential files, native OMP, or messenger SDKs.
3
- import { loadConfigSnapshot } from "./config";
3
+ import { loadConfigSnapshot } from "./config/config";
4
4
 
5
5
  const [file, ...extra] = process.argv.slice(2);
6
6
  if (!file || extra.length) throw new Error("Expected one Gateway config file");
@@ -1,9 +1,9 @@
1
1
  // One shot, under the recorded restart-runner PID. Resolve FILE.env with the
2
2
  // same private-file checks as `start`; never serialize tokens to argv or pipes.
3
3
  import { resolve } from "node:path";
4
- import { loadConfigSnapshot, requireMessengerCredentials } from "./config";
5
- import { loadCredentials } from "./credentials";
6
- import { requireGateway } from "./gateway-native";
4
+ import { loadConfigSnapshot, requireMessengerCredentials } from "./config/config";
5
+ import { loadCredentials } from "./config/credentials";
6
+ import { requireGateway } from "./gateway/gateway-native";
7
7
 
8
8
  const [file, request, originalStateDir, ...extra] = process.argv.slice(2);
9
9
  if (!file || !request || !originalStateDir || extra.length) throw new Error("Missing restart identity");
@@ -2,9 +2,9 @@ import { Database } from "bun:sqlite";
2
2
  import { existsSync } from "node:fs";
3
3
  import { isAbsolute, join } from "node:path";
4
4
  import { isDeepStrictEqual } from "node:util";
5
- import { isConfiguredRoute, type Config } from "./config";
6
- import type { Messenger } from "./contracts";
7
- import { DeliveryError } from "./delivery";
5
+ import { isConfiguredRoute, type Config } from "../config/config";
6
+ import type { Messenger } from "../contracts";
7
+ import { DeliveryError } from "../messaging/delivery";
8
8
  import { groupRoom, groupRoomKey, type GroupReply, type GroupRequest } from "./group-policy";
9
9
 
10
10
  const schema = `
@@ -132,6 +132,11 @@ export class GroupAccess {
132
132
 
133
133
  get busy(): boolean { return this.active !== undefined || this.sending !== undefined; }
134
134
  get running(): boolean { return this.active !== undefined; }
135
+ get hasWork(): boolean {
136
+ return this.busy || this.db.query(`SELECT 1 WHERE
137
+ EXISTS (SELECT 1 FROM group_requests WHERE state IN ('pending','running')) OR
138
+ EXISTS (SELECT 1 FROM group_responses WHERE state IN ('ready','attempted','uncertain'))`).get() !== null;
139
+ }
135
140
 
136
141
  private launch(report: (error: unknown) => void): void {
137
142
  try {
@@ -1,8 +1,8 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { realpathSync, statSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
- import type { Config } from "./config";
5
- import type { Platform, Route } from "./contracts";
4
+ import type { Config } from "../config/config";
5
+ import type { Platform, Route } from "../contracts";
6
6
 
7
7
  export const GROUP_MODEL_SELECTOR = /^([a-z][a-z0-9-]{0,62})\/([a-zA-Z0-9][a-zA-Z0-9._/-]{0,158})$/;
8
8