omp-superagent 0.1.9 → 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 (151) hide show
  1. package/DESIGN.md +68 -21
  2. package/README.ko.md +30 -372
  3. package/README.md +31 -419
  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 +8 -0
  11. package/docs/OPERATIONS.en.md +2277 -0
  12. package/docs/OPERATIONS.md +198 -45
  13. package/docs/design/execution.md +163 -54
  14. package/docs/design/messaging.md +125 -34
  15. package/docs/kakao-bridge-protocol.md +193 -0
  16. package/docs/releases/0.1.10.md +17 -0
  17. package/docs/releases/0.1.11.md +18 -0
  18. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  19. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  20. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  21. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  22. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  23. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  24. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  25. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  26. package/package.json +10 -11
  27. package/scripts/{prepare-ulw.ts → prepare-super.ts} +1 -1
  28. package/skills/head/SKILL.md +36 -5
  29. package/skills/head/references/routing.md +1 -1
  30. package/skills/head/references/supervision.md +32 -26
  31. package/skills/lane/SKILL.md +39 -21
  32. package/skills/lane/references/workflow.md +23 -16
  33. package/src/cli.ts +35 -33
  34. package/src/{config.ts → config/config.ts} +51 -6
  35. package/src/config/wake-config.ts +36 -0
  36. package/src/contracts.ts +91 -13
  37. package/src/{cron-jobs.ts → cron/cron-jobs.ts} +21 -13
  38. package/src/{cron-pr-intake.ts → cron/cron-pr-intake.ts} +4 -4
  39. package/src/{cron-schedule.ts → cron/cron-schedule.ts} +3 -3
  40. package/src/extension.ts +64 -28
  41. package/src/{gateway-client.ts → gateway/gateway-client.ts} +89 -32
  42. package/src/{gateway-native.ts → gateway/gateway-native.ts} +4 -4
  43. package/src/{gateway-protocol.ts → gateway/gateway-protocol.ts} +69 -14
  44. package/src/{gateway-wire.ts → gateway/gateway-wire.ts} +12 -7
  45. package/src/gateway-config.ts +1 -1
  46. package/src/gateway-restart-env.ts +3 -3
  47. package/src/{group-access.ts → group/group-access.ts} +8 -3
  48. package/src/{group-policy.ts → group/group-policy.ts} +2 -2
  49. package/src/{group-runner.ts → group/group-runner.ts} +11 -6
  50. package/src/host-extension.ts +213 -43
  51. package/src/host-sdk-helper.ts +62 -65
  52. package/src/{decision-tool.ts → lane/decision-tool.ts} +12 -4
  53. package/src/{decisions.ts → lane/decisions.ts} +12 -10
  54. package/src/{lane-models.ts → lane/lane-models.ts} +1 -1
  55. package/src/{lane-report.ts → lane/lane-report.ts} +22 -0
  56. package/src/{lane-rows.ts → lane/lane-rows.ts} +2 -2
  57. package/src/{lane-watch.ts → lane/lane-watch.ts} +6 -2
  58. package/src/{workflow.ts → lane/workflow.ts} +1 -1
  59. package/src/lane-extension.ts +69 -13
  60. package/src/managed-memory-helper.ts +2 -2
  61. package/src/{managed-ulw-probe.ts → managed-super-probe.ts} +3 -3
  62. package/src/{delivery.ts → messaging/delivery.ts} +1 -1
  63. package/src/{discord-command-registration.ts → messaging/discord-command-registration.ts} +3 -2
  64. package/src/{discord-context.ts → messaging/discord-context.ts} +1 -1
  65. package/src/{messenger-command-catalog.json → messaging/messenger-command-catalog.json} +1 -0
  66. package/src/messaging/messenger-commands.ts +55 -0
  67. package/src/{result-attachment.ts → messaging/result-attachment.ts} +3 -3
  68. package/src/{slack-command-registration.ts → messaging/slack-command-registration.ts} +3 -3
  69. package/src/{telegram-command-registration.ts → messaging/telegram-command-registration.ts} +2 -2
  70. package/src/omp/head-resume.ts +123 -0
  71. package/src/{host-owner-path.ts → omp/host-owner-path.ts} +1 -1
  72. package/src/{host-protocol.ts → omp/host-protocol.ts} +11 -2
  73. package/src/omp/host-reply-voice.ts +181 -0
  74. package/src/{host-superkit.ts → omp/host-superkit.ts} +1 -1
  75. package/src/{host.ts → omp/host.ts} +26 -17
  76. package/src/{installed-omp.ts → omp/installed-omp.ts} +1 -1
  77. package/src/{managed-memory.ts → omp/managed-memory.ts} +2 -2
  78. package/src/{managed-ulw.ts → omp/managed-super.ts} +42 -16
  79. package/src/omp/native-journal.ts +124 -0
  80. package/src/{native-launch-profile.ts → omp/native-launch-profile.ts} +6 -2
  81. package/src/{native-presets.ts → omp/native-presets.ts} +2 -2
  82. package/src/omp/native-sessions.ts +124 -0
  83. package/src/{omp-usage.ts → omp/omp-usage.ts} +1 -1
  84. package/src/omp/soul.ts +214 -0
  85. package/src/omp/stock-head-launch.ts +31 -0
  86. package/src/{autostart.ts → operator/autostart.ts} +3 -3
  87. package/src/{operator.ts → operator/operator.ts} +2 -2
  88. package/src/{setup-judge.ts → operator/setup-judge.ts} +1 -1
  89. package/src/{setup-profiles.ts → operator/setup-profiles.ts} +2 -2
  90. package/src/{setup.ts → operator/setup.ts} +7 -6
  91. package/src/{pr-intake-automation.ts → pr/pr-intake-automation.ts} +1 -1
  92. package/src/{pr-intake-mode.ts → pr/pr-intake-mode.ts} +3 -3
  93. package/src/{pr-intake-review.ts → pr/pr-intake-review.ts} +5 -5
  94. package/src/{pr-intake-work.ts → pr/pr-intake-work.ts} +1 -1
  95. package/src/{pr-review-models.ts → pr/pr-review-models.ts} +2 -2
  96. package/src/{pr-watch.ts → pr/pr-watch.ts} +36 -26
  97. package/src/{message-order.ts → routing/message-order.ts} +3 -2
  98. package/src/{topic-history.ts → routing/topic-history.ts} +2 -2
  99. package/src/{topic-request.ts → routing/topic-request.ts} +4 -2
  100. package/src/{runtime.ts → runtime/controller.ts} +1278 -1267
  101. package/src/runtime/deferred-routing.ts +106 -0
  102. package/src/runtime/dm-timeline.ts +194 -0
  103. package/src/{head-recovery.ts → runtime/head-recovery.ts} +1 -1
  104. package/src/{head-rotation.ts → runtime/head-rotation.ts} +32 -5
  105. package/src/runtime/model-journal.ts +119 -0
  106. package/src/runtime/native-frames.ts +131 -0
  107. package/src/{observation-request.ts → runtime/observation-request.ts} +1 -1
  108. package/src/runtime/preset-sync.ts +232 -0
  109. package/src/runtime/preset-watch-paths.ts +137 -0
  110. package/src/runtime/result-attachments.ts +146 -0
  111. package/src/storage/deferred-routing.ts +149 -0
  112. package/src/{store.ts → storage/store.ts} +450 -49
  113. package/src/{worker-bridge.ts → worker/worker-bridge.ts} +2 -2
  114. package/src/{worker-enrollment.ts → worker/worker-enrollment.ts} +2 -2
  115. package/src/{worker-host.ts → worker/worker-host.ts} +7 -3
  116. package/src/{worker-placement.ts → worker/worker-placement.ts} +1 -1
  117. package/src/{worker-profile.ts → worker/worker-profile.ts} +1 -1
  118. package/src/{worker-registration.ts → worker/worker-registration.ts} +2 -2
  119. package/src/{worker-request.ts → worker/worker-request.ts} +5 -5
  120. package/src/{worker-service.ts → worker/worker-service.ts} +2 -2
  121. package/src/{worker-trust.ts → worker/worker-trust.ts} +1 -1
  122. package/src/{worker-wire.ts → worker/worker-wire.ts} +3 -3
  123. package/src/worker-serve-prepare.ts +4 -4
  124. package/src/board-extension.ts +0 -217
  125. package/src/board.ts +0 -467
  126. package/src/gateway-host-helper.ts +0 -13
  127. package/src/messenger-commands.ts +0 -15
  128. package/src/native-sessions.ts +0 -34
  129. /package/src/{credentials.ts → config/credentials.ts} +0 -0
  130. /package/src/{dialog.ts → messaging/dialog.ts} +0 -0
  131. /package/src/{telegram-command-languages.json → messaging/telegram-command-languages.json} +0 -0
  132. /package/src/{host-broker-services.ts → omp/host-broker-services.ts} +0 -0
  133. /package/src/{host-inventory-manifest.ts → omp/host-inventory-manifest.ts} +0 -0
  134. /package/src/{host-services.ts → omp/host-services.ts} +0 -0
  135. /package/src/{native-settings.ts → omp/native-settings.ts} +0 -0
  136. /package/src/{superkit-skills.ts → omp/superkit-skills.ts} +0 -0
  137. /package/src/{repository.ts → operator/repository.ts} +0 -0
  138. /package/src/{pr-github-schema.ts → pr/pr-github-schema.ts} +0 -0
  139. /package/src/{pr-github.ts → pr/pr-github.ts} +0 -0
  140. /package/src/{pr-intake-comment.ts → pr/pr-intake-comment.ts} +0 -0
  141. /package/src/{pr-intake-fix.ts → pr/pr-intake-fix.ts} +0 -0
  142. /package/src/{pr-intake-github.ts → pr/pr-intake-github.ts} +0 -0
  143. /package/src/{pr-intake-material.ts → pr/pr-intake-material.ts} +0 -0
  144. /package/src/{pr-intake-tree.ts → pr/pr-intake-tree.ts} +0 -0
  145. /package/src/{head-quota.ts → runtime/head-quota.ts} +0 -0
  146. /package/src/{worker-checkout.ts → worker/worker-checkout.ts} +0 -0
  147. /package/src/{worker-destination.ts → worker/worker-destination.ts} +0 -0
  148. /package/src/{worker-doctor.ts → worker/worker-doctor.ts} +0 -0
  149. /package/src/{worker-ledger.ts → worker/worker-ledger.ts} +0 -0
  150. /package/src/{worker-repository.ts → worker/worker-repository.ts} +0 -0
  151. /package/upstream/{ulw.json → super.json} +0 -0
@@ -3,9 +3,10 @@ import { lstatSync, readFileSync, realpathSync } from "node:fs";
3
3
  import { chmod, link, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, writeFile } from "node:fs/promises";
4
4
  import { dirname, isAbsolute, join, resolve, sep } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
- import type { WorkerHostProfile } from "./worker-profile";
6
+ import type { WorkerHostProfile } from "../worker/worker-profile";
7
+ import type { NativeProfile, NativeProfileBinding, NativeProfilePaths } from "./native-sessions";
7
8
 
8
- const projectRoot = fileURLToPath(new URL("../", import.meta.url));
9
+ const projectRoot = fileURLToPath(new URL("../../", import.meta.url));
9
10
  const ownership = "omp-superagent-managed-ulw-v1";
10
11
  const hash = /^[0-9a-f]{40,64}$/;
11
12
  export const MANAGED_ULW_ENV = "OMP_SUPERAGENT_MANAGED_ULW_PATH";
@@ -53,7 +54,7 @@ function matchesUlwRepository(previous: string, current: string): boolean {
53
54
  );
54
55
  }
55
56
 
56
- export function readUlwManifest(manifestPath = join(projectRoot, "upstream/ulw.json")): UlwManifest {
57
+ export function readUlwManifest(manifestPath = join(projectRoot, "upstream/super.json")): UlwManifest {
57
58
  const value = JSON.parse(readFileSync(manifestPath, "utf8")) as UlwManifest;
58
59
  if (!value.repository || value.ref !== "HEAD" || !value.directory ||
59
60
  !Number.isSafeInteger(value.checkIntervalMs) || value.checkIntervalMs < 60_000 ||
@@ -185,7 +186,7 @@ async function probe(packagePath: string, stage: string, manifest: UlwManifest):
185
186
  PI_CODING_AGENT_DIR: join(home, "agent"), XDG_CONFIG_HOME: join(home, "config"),
186
187
  XDG_DATA_HOME: join(home, "data"), XDG_CACHE_HOME: join(home, "cache"), CI: "true", NO_COLOR: "1" };
187
188
  if (process.env.PI_NATIVES_DIR) env.PI_NATIVES_DIR = process.env.PI_NATIVES_DIR;
188
- await run([process.execPath, fileURLToPath(new URL("./managed-ulw-probe.ts", import.meta.url)), packagePath],
189
+ await run([process.execPath, fileURLToPath(new URL("../managed-super-probe.ts", import.meta.url)), packagePath],
189
190
  home, manifest.probeTimeoutMs, env);
190
191
  }
191
192
 
@@ -200,6 +201,7 @@ export type ManagedUlwLaunchInput = {
200
201
  /** Exact native OMP argv, including the original command's flags and generated Host args; no executable prefix. */
201
202
  launchArgs: string[];
202
203
  worker?: Pick<WorkerHostProfile, "extensionPaths">;
204
+ expectedNativeProfile?: NativeProfile;
203
205
  };
204
206
  type ManagedUlwLaunchOptions = Omit<ManagedUlwLaunchInput, "managedUlwPath"> & {
205
207
  managedUlwPath?: string;
@@ -207,7 +209,14 @@ type ManagedUlwLaunchOptions = Omit<ManagedUlwLaunchInput, "managedUlwPath"> & {
207
209
  bunCommand: string[];
208
210
  discoveryTimeoutMs?: number;
209
211
  };
210
- export type ManagedUlwLaunchComposition = { extensionPaths: string[]; noExtensions: boolean; memoryWriteDir: string | null };
212
+ export type ManagedUlwLaunchComposition = {
213
+ extensionPaths: string[];
214
+ noExtensions: boolean;
215
+ memoryWriteDir: string | null;
216
+ nativeProfile?: NativeProfile;
217
+ nativeProfilePaths?: NativeProfilePaths;
218
+ nativeDotenvPaths?: string[];
219
+ };
211
220
 
212
221
  const LAUNCH_DISCOVERY_TIMEOUT_MS = 30_000;
213
222
  const LAUNCH_OUTPUT_LIMIT = 16 * 1024 * 1024; // Same bound as the Rust Gateway.
@@ -255,7 +264,7 @@ export async function managedUlwLaunch(options: ManagedUlwLaunchOptions, prepare
255
264
  }): Promise<{ composition: ManagedUlwLaunchComposition; prepared?: string; deadline?: number }> {
256
265
  if (!options.bunCommand.length) throw new Error("Managed ULW discovery requires the launcher's Bun command");
257
266
  const { env, bunCommand, discoveryTimeoutMs = LAUNCH_DISCOVERY_TIMEOUT_MS, ...input } = options;
258
- const helper = fileURLToPath(new URL("./host-sdk-helper.ts", import.meta.url));
267
+ const helper = fileURLToPath(new URL("../host-sdk-helper.ts", import.meta.url));
259
268
  const child = Bun.spawn([...bunCommand, ...(input.worker ? ["--no-install"] : []), helper, "launch"], {
260
269
  cwd: input.worker ? dirname(options.configPath) : options.cwd,
261
270
  env: Object.fromEntries(Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined)),
@@ -337,7 +346,7 @@ export async function managedUlwLaunchComposition(input: ManagedUlwLaunchInput):
337
346
  }
338
347
 
339
348
  async function workerLaunchComposition(input: ManagedUlwLaunchInput & { worker: Pick<WorkerHostProfile, "extensionPaths"> }): Promise<ManagedUlwLaunchComposition> {
340
- const { assertWorkerWorkspaceStartup } = await import("./worker-profile");
349
+ const { assertWorkerWorkspaceStartup } = await import("../worker/worker-profile");
341
350
  const { homedir } = await import("node:os");
342
351
  assertWorkerWorkspaceStartup(input.cwd, homedir());
343
352
  const { parseNativeLaunch } = await import("./native-launch-profile");
@@ -380,19 +389,31 @@ async function launchComposition(input: ManagedUlwLaunchInput): Promise<ManagedU
380
389
  const { discoverCustomCommands } = await import("@oh-my-pi/pi-coding-agent/extensibility/custom-commands/loader");
381
390
  const { getAgentDir } = await import("@oh-my-pi/pi-utils");
382
391
  const { homedir } = await import("node:os");
383
- if (parsed.pluginDirs?.length) await injectPluginDirRoots(homedir(), parsed.pluginDirs, cwd);
384
- else await preloadPluginRoots(homedir(), cwd);
385
- const { ensureManagedMemory, memoryBlockReason } = await import("./managed-memory");
386
- const settings = await Settings.loadReadOnly({ cwd, agentDir: getAgentDir(), configFiles: parsed.config })
387
- .catch(() => { throw new Error(memoryBlockReason({ status: "unknown" })); });
392
+ const { matchesNativeProfile, resolveNativeProfile, sdkNativeProfilePaths } = await import("./native-sessions");
393
+ const nativeProfilePaths = sdkNativeProfilePaths(getAgentDir());
394
+ const nativeProfile = resolveNativeProfile(nativeProfilePaths);
395
+ const roots = { nativeProfile, nativeProfilePaths, nativeDotenvPaths: parsed.nativeDotenvPaths };
396
+ if (input.expectedNativeProfile && !matchesNativeProfile(nativeProfilePaths, input.expectedNativeProfile)) {
397
+ // The Gateway consumes the observed roots to fence this wake before it
398
+ // offers a preparation manifest or permits native memory fallback writes.
399
+ return { extensionPaths: [], noExtensions: true, memoryWriteDir: null, ...roots };
400
+ }
388
401
  let memoryWriteDir: string | null = parsed.launchAgentDir;
389
402
  if (input.parentConfigPath) {
390
403
  // A lane inherits its head's post-dotenv environment. It cannot use that
391
404
  // environment to enlarge the write authority recorded by the head's launcher.
392
- const parent: unknown = await Bun.file(join(dirname(input.parentConfigPath), "owner.json")).json().catch(() => null);
393
- if (!parent || typeof parent !== "object" || !("configPath" in parent) || parent.configPath !== input.parentConfigPath ||
394
- !("memoryWriteDir" in parent) || parent.memoryWriteDir !== memoryWriteDir) memoryWriteDir = null;
405
+ const parent: { configPath?: string; memoryWriteDir?: string; nativeProfileBinding?: NativeProfileBinding } | null =
406
+ await Bun.file(join(dirname(input.parentConfigPath), "owner.json")).json().catch(() => null);
407
+ if (parent?.configPath !== input.parentConfigPath || parent.memoryWriteDir !== memoryWriteDir) memoryWriteDir = null;
408
+ if (parent?.configPath === input.parentConfigPath && parent.nativeProfileBinding &&
409
+ !matchesNativeProfile(nativeProfilePaths, parent.nativeProfileBinding.profile))
410
+ throw new Error("Native lane discovery profile differs from its managed HEAD");
395
411
  }
412
+ if (parsed.pluginDirs?.length) await injectPluginDirRoots(homedir(), parsed.pluginDirs, cwd);
413
+ else await preloadPluginRoots(homedir(), cwd);
414
+ const { ensureManagedMemory, memoryBlockReason } = await import("./managed-memory");
415
+ const settings = await Settings.loadReadOnly({ cwd, agentDir: getAgentDir(), configFiles: parsed.config })
416
+ .catch(() => { throw new Error(memoryBlockReason({ status: "unknown" })); });
396
417
  let composition: { extensionPaths: string[]; noExtensions: boolean };
397
418
  const restore = initializeWithSettings(settings);
398
419
  try {
@@ -510,9 +531,14 @@ async function launchComposition(input: ManagedUlwLaunchInput): Promise<ManagedU
510
531
  // Discovery can refuse an incompatible launch. Do not persist memory for it.
511
532
  const { readNativeSettings } = await import("./native-settings");
512
533
  const current = await readNativeSettings(settings).catch(() => { throw new Error(memoryBlockReason({ status: "unknown" })); });
534
+ if (!matchesNativeProfile(sdkNativeProfilePaths(current.getAgentDir()), nativeProfile))
535
+ throw new Error("Native profile changed during launch discovery");
513
536
  const { memory } = await ensureManagedMemory(current, memoryWriteDir);
514
537
  if (memory.status !== "enabled") throw new Error(memoryBlockReason(memory));
515
- return { ...composition, memoryWriteDir };
538
+ // Recheck the earlier observation before handing off to journal preparation.
539
+ if (!matchesNativeProfile(sdkNativeProfilePaths(settings.getAgentDir()), nativeProfile))
540
+ throw new Error("Native profile changed during launch discovery");
541
+ return { ...composition, memoryWriteDir, ...roots };
516
542
  }
517
543
 
518
544
  /** Serialized source preparation only. No Gateway, account adapter, or Host starts here. */
@@ -0,0 +1,124 @@
1
+ import { constants, type Stats } from "node:fs";
2
+ import { open, stat, type FileHandle } from "node:fs/promises";
3
+
4
+ // OMP 19.2.1 docs/session.md: JSONL with an optional initial title slot.
5
+ // Older versions share the header identity; native resume owns migrations.
6
+ const HEADER_LIMIT = 1024 * 1024;
7
+ const CHUNK_BYTES = 16 * 1024;
8
+ const utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
9
+
10
+ type Entry = Readonly<Record<string, unknown>> & { readonly type: string };
11
+ type FileIdentity = Pick<Stats, "dev" | "ino">;
12
+ type Journal = { readonly file: FileHandle; readonly initial: Stats };
13
+
14
+ export class NativeJournalFormatError extends Error {
15
+ constructor() { super("Unrecognized or incomplete native session journal"); }
16
+ }
17
+
18
+ function sameFile(left: FileIdentity, right: FileIdentity): boolean {
19
+ return left.ino === right.ino && left.dev === right.dev;
20
+ }
21
+
22
+ async function openJournal(path: string, expected?: FileIdentity): Promise<Journal | undefined> {
23
+ let file: FileHandle;
24
+ try {
25
+ file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK | (expected ? constants.O_NOFOLLOW : 0));
26
+ } catch (error) {
27
+ if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
28
+ return undefined;
29
+ throw error;
30
+ }
31
+ try {
32
+ const initial = await file.stat();
33
+ if (!initial.isFile() || expected && !sameFile(initial, expected)) throw new NativeJournalFormatError();
34
+ return { file, initial };
35
+ } catch (error) {
36
+ await file.close();
37
+ throw error;
38
+ }
39
+ }
40
+
41
+ function isEntry(value: unknown): value is Entry {
42
+ return typeof value === "object" && value !== null && !Array.isArray(value)
43
+ && "type" in value && typeof value.type === "string";
44
+ }
45
+
46
+ function titleSlot(entry: Entry): boolean {
47
+ return entry.type === "title" && entry.v === 1 && typeof entry.title === "string"
48
+ && typeof entry.updatedAt === "string" && typeof entry.pad === "string"
49
+ && (entry.source === undefined || entry.source === "auto" || entry.source === "user");
50
+ }
51
+
52
+ /** Only a complete title record on the first physical line is outside the journal. */
53
+ function titleSlotEnd(prefix: Buffer): number {
54
+ const lf = prefix.indexOf(0x0a);
55
+ if (lf < 0) return 0;
56
+ try {
57
+ const entry: unknown = JSON.parse(utf8.decode(prefix.subarray(0, lf)).trim());
58
+ return isEntry(entry) && titleSlot(entry) ? lf + 1 : 0;
59
+ } catch (error) {
60
+ if (error instanceof SyntaxError || error instanceof TypeError) return 0;
61
+ throw error;
62
+ }
63
+ }
64
+
65
+ function headerId(prefix: Buffer): string | undefined {
66
+ // Stock trims the physical title line, but skips only JSON whitespace
67
+ // before a header. In particular, a BOM is not a header prefix.
68
+ let start = titleSlotEnd(prefix);
69
+ while (start < prefix.length) {
70
+ const byte = prefix[start];
71
+ if (byte !== 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0d) break;
72
+ start++;
73
+ }
74
+ if (prefix[start] !== 0x7b) return undefined;
75
+
76
+ // A header can span lines. Decode through its closing brace, not the body.
77
+ let depth = 0;
78
+ let quoted = false;
79
+ for (let i = start; i < prefix.length; i++) {
80
+ const byte = prefix[i];
81
+ if (quoted && byte === 0x5c) { i++; continue; } // escaped byte inside a string
82
+ if (byte === 0x22) quoted = !quoted;
83
+ if (quoted) continue;
84
+ if (byte === 0x7b) depth++;
85
+ if (byte !== 0x7d) continue;
86
+ depth--;
87
+ if (depth !== 0) continue;
88
+ try {
89
+ const entry: unknown = JSON.parse(utf8.decode(prefix.subarray(start, i + 1)));
90
+ if (isEntry(entry) && entry.type === "session" && typeof entry.id === "string" && entry.id) return entry.id;
91
+ // A complete title object can still be waiting for its physical newline.
92
+ return undefined;
93
+ } catch (error) {
94
+ if (!(error instanceof SyntaxError || error instanceof TypeError)) throw error;
95
+ }
96
+ throw new NativeJournalFormatError();
97
+ }
98
+ return undefined;
99
+ }
100
+
101
+ /** Read a bounded identity prefix. Only a missing path is reported as absent. */
102
+ export async function readNativeSessionId(path: string, expected?: FileIdentity): Promise<string | undefined> {
103
+ const journal = await openJournal(path, expected);
104
+ if (!journal) return undefined;
105
+ try {
106
+ const limit = Math.min(journal.initial.size, HEADER_LIMIT);
107
+ let prefix = Buffer.alloc(0);
108
+ while (prefix.length < limit) {
109
+ const remaining = Math.min(limit - prefix.length, Math.max(CHUNK_BYTES, prefix.length));
110
+ const chunk = Buffer.allocUnsafe(remaining);
111
+ const { bytesRead } = await journal.file.read(chunk, 0, remaining, prefix.length);
112
+ if (!bytesRead) break;
113
+ const read = chunk.subarray(0, bytesRead);
114
+ prefix = prefix.length ? Buffer.concat([prefix, read]) : read;
115
+ const id = headerId(prefix);
116
+ if (id !== undefined) {
117
+ if (!sameFile(journal.initial, await stat(path))) throw new NativeJournalFormatError();
118
+ return id;
119
+ }
120
+ }
121
+ throw new NativeJournalFormatError();
122
+ } finally { await journal.file.close(); }
123
+ }
124
+
@@ -1,11 +1,15 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+
1
4
  /** Stock OMP chooses its profile before settings or discovery import native dotenv. */
2
5
  export async function parseNativeLaunch(launchArgs: readonly string[]) {
3
6
  const { extractProfileFlags } = await import("@oh-my-pi/pi-coding-agent/cli/profile-bootstrap");
4
- const { getAgentDir, setProfile, resolveProfileEnv } = await import("@oh-my-pi/pi-utils/dirs");
7
+ const { getAgentDir, getConfigRootDir, getProjectDir, setProfile, resolveProfileEnv } = await import("@oh-my-pi/pi-utils/dirs");
5
8
  const bootstrap = extractProfileFlags(launchArgs);
6
9
  setProfile(bootstrap.profile ?? resolveProfileEnv(process.env.OMP_PROFILE, process.env.PI_PROFILE));
7
10
  // Capture the operator's destination before native launch imports load workspace dotenv.
8
11
  const launchAgentDir = getAgentDir();
12
+ const nativeDotenvPaths = [getProjectDir(), launchAgentDir, getConfigRootDir(), homedir()].map(dir => join(dir, ".env"));
9
13
  if (bootstrap.aliasName !== undefined) throw new Error("Managed Hosts cannot install native aliases");
10
14
  const { isNativeShell } = await import("@oh-my-pi/pi-coding-agent/cli/native-shell");
11
15
  if (isNativeShell(bootstrap.argv[0])) throw new Error("Managed Hosts require native launch argv, not a shell command");
@@ -14,5 +18,5 @@ export async function parseNativeLaunch(launchArgs: readonly string[]) {
14
18
  if ("error" in resolved) throw new Error(resolved.error);
15
19
  if (resolved.argv[0] !== "launch") throw new Error("Managed Hosts require native OMP launch argv");
16
20
  const { parseArgs } = await import("@oh-my-pi/pi-coding-agent/cli/args");
17
- return { ...parseArgs(resolved.argv.slice(1)), launchAgentDir };
21
+ return { ...parseArgs(resolved.argv.slice(1)), launchAgentDir, nativeDotenvPaths };
18
22
  }
@@ -7,8 +7,8 @@ import { acquireModelRoleMutation, getModelPreset, getModelPresetNames, isValidM
7
7
  import { pickDefaultAvailableModel, resolveModelRoleValue } from "@oh-my-pi/pi-coding-agent/config/model-resolver";
8
8
  import type { Settings, SettingsMirrorState } from "@oh-my-pi/pi-coding-agent/config/settings";
9
9
  import { cfgDefaultThinkingLevel } from "@oh-my-pi/pi-coding-agent/session/settings";
10
- import { MODEL_PRESET_NAMES, type LaneModel, type LanePresetSnapshot, type ResolvedLanePreset, type StorePort } from "./contracts";
11
- import { isLaneModel, sameLaneModel } from "./lane-models";
10
+ import { MODEL_PRESET_NAMES, type LaneModel, type LanePresetSnapshot, type ResolvedLanePreset, type StorePort } from "../contracts";
11
+ import { isLaneModel, sameLaneModel } from "../lane/lane-models";
12
12
  import { editNativeGlobalConfig, hasUnresolvedNativeLegacy, readNativeSettings } from "./native-settings";
13
13
 
14
14
  export type NativeModel = Awaited<ReturnType<ExtensionContext["models"]["list"]>>[number];
@@ -0,0 +1,124 @@
1
+ import * as fs from "node:fs/promises";
2
+ import { lstatSync, realpathSync, statSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { getAgentDbPath, getAgentDir, getSessionsDir } from "@oh-my-pi/pi-utils/dirs";
6
+ import { readSessionInfo } from "@oh-my-pi/pi-coding-agent/session/session-listing";
7
+ import { sessionDirForCwd } from "@oh-my-pi/pi-coding-agent/session/session-paths";
8
+
9
+ export const NATIVE_PROFILE_ENV = "OMP_SUPERAGENT_NATIVE_PROFILE";
10
+
11
+ export type NativeProfilePaths = {
12
+ readonly agentDir: string;
13
+ readonly dataDir: string;
14
+ readonly sessionsDir: string;
15
+ };
16
+
17
+ export type NativeProfile = NativeProfilePaths & { readonly version: 2 };
18
+
19
+ export type NativeProfileBinding = {
20
+ readonly profile: NativeProfile;
21
+ readonly discoveryEntry: string;
22
+ };
23
+
24
+ export type HostReadyEvent = {
25
+ readonly pid: number;
26
+ readonly sessionId: string;
27
+ readonly sessionFile: string;
28
+ readonly nativeProfile?: NativeProfile;
29
+ readonly waking?: boolean;
30
+ };
31
+
32
+ export function sdkNativeProfilePaths(agentDir = getAgentDir()): NativeProfilePaths {
33
+ return { agentDir, dataDir: dirname(getAgentDbPath(agentDir)), sessionsDir: getSessionsDir() };
34
+ }
35
+
36
+ function isMissing(error: unknown): boolean {
37
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
38
+ }
39
+
40
+ /** Resolve through existing ancestors without creating directories or accepting dangling symlinks. */
41
+ function canonicalDirectory(path: string): string {
42
+ if (!isAbsolute(path)) throw new Error("Native profile paths must be absolute");
43
+ const stat = lstatSync(path, { throwIfNoEntry: false });
44
+ if (!stat) return join(canonicalDirectory(dirname(path)), basename(path));
45
+ const canonical = realpathSync(path);
46
+ if (!(stat.isSymbolicLink() ? statSync(canonical) : stat).isDirectory())
47
+ throw new Error("Native profile path is not a directory");
48
+ return canonical;
49
+ }
50
+
51
+ export function resolveNativeProfile(paths: NativeProfilePaths): NativeProfile {
52
+ return { version: 2, agentDir: canonicalDirectory(paths.agentDir), dataDir: canonicalDirectory(paths.dataDir),
53
+ sessionsDir: canonicalDirectory(paths.sessionsDir) };
54
+ }
55
+
56
+ export function matchesNativeProfile(paths: NativeProfilePaths, profile: NativeProfile): boolean {
57
+ return isDeepStrictEqual(resolveNativeProfile(paths), profile);
58
+ }
59
+
60
+ /** Use the injected stock SDK, not a second resolver from node_modules. */
61
+ export async function bindNativeProfile(
62
+ native: Pick<typeof import("@oh-my-pi/pi-coding-agent"), "findSessionFiles" | "getAgentDir">,
63
+ session: { readonly agentDir: string; readonly file: string; readonly id: string },
64
+ binding: NativeProfileBinding,
65
+ ): Promise<NativeProfilePaths> {
66
+ const mismatch = () => new Error("Running native Host does not match the prepared agent, data and discovery roots");
67
+ if (native.getAgentDir() !== session.agentDir) throw mismatch();
68
+ const source = realpathSync(session.file);
69
+ const preparedBucket = dirname(binding.discoveryEntry);
70
+ if (dirname(preparedBucket) !== binding.profile.sessionsDir || canonicalDirectory(preparedBucket) !== preparedBucket
71
+ || realpathSync(binding.discoveryEntry) !== source) throw mismatch();
72
+ // Unlike getDefaultSessionDir, the stock search does not create project
73
+ // buckets or migrate files. Its default root is the native process's data
74
+ // partition, independent of the npm SDK's ambient directory resolver. It
75
+ // may deduplicate legitimate aliases, so compare the owned journal itself.
76
+ for (const entry of await native.findSessionFiles(session.id)) {
77
+ const sessionsDir = dirname(dirname(entry));
78
+ const paths = { agentDir: session.agentDir, dataDir: dirname(sessionsDir), sessionsDir };
79
+ if (matchesNativeProfile(paths, binding.profile) && realpathSync(entry) === source) return paths;
80
+ }
81
+ throw mismatch();
82
+ }
83
+
84
+ /** Stock OMP follows leaf session links for discovery and writes through them. */
85
+ export async function publishNativeSession(
86
+ sessionFile: string, cwd: string, expectedId?: string, profile = resolveNativeProfile(sdkNativeProfilePaths()),
87
+ ): Promise<string | undefined> {
88
+ const info = await readSessionInfo(sessionFile);
89
+ if (!info) return;
90
+ if (expectedId !== undefined && (info.id !== expectedId || info.cwd !== cwd))
91
+ throw new Error("Refusing to publish a journal with a different managed session identity");
92
+ const source = await fs.realpath(sessionFile);
93
+ const directory = sessionDirForCwd(cwd, profile.sessionsDir);
94
+ const target = join(directory, `${info.created.toISOString().replace(/[:.]/g, "-")}_${info.id}.jsonl`);
95
+ if (target === source) return target;
96
+
97
+ const requireBucket = () => {
98
+ if (!matchesNativeProfile(profile, profile) || canonicalDirectory(directory) !== directory)
99
+ throw new Error("Native discovery directory no longer belongs to the prepared profile");
100
+ };
101
+ requireBucket();
102
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
103
+ const link = async (original: string, destination: string) => {
104
+ requireBucket();
105
+ try { await fs.symlink(original, destination); }
106
+ catch (error) {
107
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
108
+ const existing = await fs.readlink(destination).catch(error => {
109
+ if (isMissing(error) || (error instanceof Error && "code" in error && error.code === "EINVAL")) return;
110
+ throw error;
111
+ });
112
+ if (!existing || resolve(dirname(destination), existing) !== original)
113
+ throw new Error(`Native session discovery path already belongs to another file: ${destination}`);
114
+ }
115
+ };
116
+ // The resumed session must keep its original spill artifacts and child journals.
117
+ if (source.endsWith(".jsonl")) {
118
+ const artifacts = source.slice(0, -".jsonl".length);
119
+ await fs.mkdir(artifacts, { recursive: true, mode: 0o700 });
120
+ await link(artifacts, target.slice(0, -".jsonl".length));
121
+ }
122
+ await link(source, target);
123
+ return target;
124
+ }
@@ -3,7 +3,7 @@ import { delimiter } from "node:path";
3
3
  import { extractProfileFlags } from "@oh-my-pi/pi-coding-agent/cli/profile-bootstrap";
4
4
  import { Type, type Static } from "@sinclair/typebox/type";
5
5
  import { Value } from "@sinclair/typebox/value";
6
- import { credentialEnvNames, type Config } from "./config";
6
+ import { credentialEnvNames, type Config } from "../config/config";
7
7
 
8
8
  // Parse only fields used from the CLI JSON. The stock extension loader does not
9
9
  // resolve the SDK usage module's internal omptype import.
@@ -0,0 +1,214 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import type { Inbound, StorePort } from "../contracts";
3
+ import { ownerRoutingProse, transportRoutingProse } from "../routing/topic-history";
4
+
5
+ const dimensions = {
6
+ concept: {
7
+ plain: "",
8
+ editorial: "Use an editorial presentation: distill the relevant points and make distinctions precise within the requested format.",
9
+ mentoring: "Use a mentoring presentation: make the reasoning easy to follow and use a concrete example when it fits the requested format.",
10
+ },
11
+ tone: {
12
+ direct: "Be candid and matter-of-fact without being curt.",
13
+ warm: "Sound warm and approachable without adding filler.",
14
+ neutral: "Use a calm, neutral tone.",
15
+ },
16
+ register: {
17
+ natural: "Match the operator's register.",
18
+ formal: "Use a respectful, formal register (존댓말 in Korean).",
19
+ casual: "Use a relaxed, conversational register.",
20
+ },
21
+ detail: {
22
+ balanced: "Give the context needed to use the answer.",
23
+ brief: "Keep the answer brief unless the operator asks for depth.",
24
+ detailed: "Include relevant context and explanation.",
25
+ },
26
+ structure: {
27
+ "answer-first": "Lead with the answer, result, or blocker.",
28
+ "evidence-first": "Present the key evidence before the conclusion.",
29
+ natural: "Organize the answer naturally for the question.",
30
+ },
31
+ emoji: {
32
+ none: "Do not add decorative emoji.",
33
+ light: "Use an occasional emoji only where it reads naturally.",
34
+ },
35
+ } as const;
36
+
37
+ type Voice = { [D in keyof typeof dimensions]: keyof typeof dimensions[D] };
38
+ const requests = {
39
+ concept: {
40
+ plain: /\b(?:plain|no particular) (?:concept|persona|style)\b|컨셉\s*(?:없이|빼고)|기본\s*컨셉/u,
41
+ editorial: /\b(?:like an? editor|editorial (?:voice|style|approach|concept)|editor(?:-like)? (?:voice|style|approach|concept))\b|(?:편집장|편집자|에디터)\s*(?:처럼|같이|같은|스타일|컨셉|콘셉트?|느낌|말투)/u,
42
+ mentoring: /\b(?:like (?:a|my) (?:mentor|coach)|(?:mentor|coach)(?:-like|ing)? (?:voice|style|approach|concept))\b|(?:멘토|코치|(?:옆자리|옆에 있는|일 잘하는)\s*선배|선배)\s*(?:처럼|같이|같은|스타일|컨셉|콘셉트?|느낌|말투)/u,
43
+ },
44
+ tone: {
45
+ direct: /\b(?:candid|straightforward|matter-of-fact|direct(?:ly)?|blunt(?:ly)?)\b|단도직입|직설적|담백/u,
46
+ warm: /\b(?:warm(?:er|ly)?|friendl(?:y|ier)|approachable)\b|따뜻|친근|다정/u,
47
+ neutral: /\b(?:neutral(?:ly)?|calm(?:ly)?)\b|중립적|차분/u,
48
+ },
49
+ register: {
50
+ natural: /\b(?:my|match my|mirror my) register\b|내 말투에 맞/u,
51
+ formal: /\b(?:formally|respectfully|politely|(?:formal|respectful|polite)(?=\s*(?:[,!.]|$)|\s+(?:tone|language|voice|register|style|replies|and)\b))\b|존댓말|격식\s*있게|예의\s*있게|공손(?:하게|히)/u,
52
+ casual: /\b(?:casual(?:ly)?|informal(?:ly)?|conversational)\b|반말|격식 없이/u,
53
+ },
54
+ detail: {
55
+ balanced: /\bbalanced (?:detail|length)\b|적당한 분량/u,
56
+ brief: /\b(?:brief(?:ly)?|concis(?:e|ely)|shorter|short replies)\b|짧(?:게|고)|간결하게|간단하게/u,
57
+ detailed: /\b(?:detailed|in detail|more detail|thorough(?:ly)?)\b|자세하게|상세하게/u,
58
+ },
59
+ structure: {
60
+ "answer-first": /\b(?:answer|conclusion|result) first\b|(?:결론|결과|답|핵심|요점)\s*(?:부터|을\s*먼저)/u,
61
+ "evidence-first": /\b(?:evidence|reasoning) first\b|근거부터/u,
62
+ natural: /\bnatural (?:structure|order)\b|자연스러운 순서/u,
63
+ },
64
+ emoji: {
65
+ none: /\b(?:no|without) emoji(?:s)?\b|(?:이모지|이모티콘)\s*(?:없이|빼고|금지|쓰지\s*말)/u,
66
+ light: /\b(?:occasional|light|use some) emoji(?:s)?\b|(?:가끔|가벼운)\s*(?:이모지|이모티콘)/u,
67
+ },
68
+ } satisfies { [D in keyof Voice]: Record<Voice[D], RegExp> };
69
+ const defaultVoice = {
70
+ concept: "plain", tone: "direct", register: "natural", detail: "balanced", structure: "answer-first", emoji: "none",
71
+ } satisfies Voice;
72
+ const setting = "soul:reply-voice";
73
+
74
+ export const soulUpdateSchema = Type.Object({
75
+ sourceId: Type.String({ minLength: 1, pattern: "\\S" }),
76
+ }, { additionalProperties: false });
77
+ type SoulUpdate = Partial<Voice> | "reset";
78
+ type Ledger = Pick<StorePort, "getMeta" | "setMeta">;
79
+
80
+ function object(value: unknown): value is Record<string, unknown> {
81
+ return typeof value === "object" && value !== null && !Array.isArray(value);
82
+ }
83
+
84
+ function voicePatch(value: unknown): value is Partial<Voice> {
85
+ return object(value) && Object.keys(value).length > 0 && Object.entries(value).every(([key, choice]) =>
86
+ Object.hasOwn(dimensions, key) && typeof choice === "string" && Object.hasOwn(dimensions[key as keyof Voice], choice));
87
+ }
88
+
89
+ function completeVoice(value: unknown) {
90
+ // Both persisted pre-concept profiles and the first native wire version
91
+ // have all the original fields but no concept.
92
+ if (!voicePatch(value) || Object.keys(defaultVoice).some(key => key !== "concept" && !Object.hasOwn(value, key)))
93
+ throw new Error("Invalid reply voice profile");
94
+ return { ...defaultVoice, ...value };
95
+ }
96
+
97
+ function savedVoice(store: Ledger) {
98
+ const raw = store.getMeta(setting);
99
+ if (raw === null) return { revision: 0, sourceId: null, style: defaultVoice };
100
+ const saved: unknown = JSON.parse(raw);
101
+ if (!object(saved) || Object.keys(saved).length !== 3 || typeof saved.revision !== "number"
102
+ || !Number.isSafeInteger(saved.revision) || saved.revision < 1 || typeof saved.sourceId !== "string" || !saved.sourceId)
103
+ throw new Error("Stored reply voice is invalid");
104
+ return { revision: saved.revision, sourceId: saved.sourceId, style: completeVoice(saved.style) };
105
+ }
106
+
107
+ function startsWithPresentation(text: string): boolean {
108
+ return Object.values(requests).some(choices => Object.values(choices).some(pattern => pattern.exec(text)?.index === 0));
109
+ }
110
+
111
+ function onlyPresentationGrammar(text: string): boolean {
112
+ // Every non-choice word must be reply syntax, not a task, exception, example
113
+ // or time/channel qualifier. This also prevents a negated choice from
114
+ // becoming affirmative just because its vocabulary matched a dimension.
115
+ const english = /\b(?:please|answer|answers|reply|replies|respond|response|responses|explain|use|keep|make|be|your|my|our|the|a|an|it|in|with|and|to|as|more|tone|register|length|style|voice|approach|concept|format)\b/gu;
116
+ const korean = /(?:답변|응답|말투|톤|분량|방식|스타일|컨셉|콘셉트?)(?:으로|은|는|을|를|이|가)?|(?:으로|하게|있게|해서|하고|이며|이고|면서|그리고|또|좀|더|늘|항상|기본적으로|답해|말해|설명해|알려|써|해|바꿔|변경해|설정해|정해|부탁해|부탁드려요|줘|주세요|주라|서|로|게)/gu;
117
+ return !text.replace(english, " ").replace(korean, " ").replace(/[\s,.!,。、]+/gu, "");
118
+ }
119
+
120
+ /** Only unambiguous, supported choices in the original author's own prose are saved. */
121
+ export function soulUpdateIntent(source: Inbound): SoulUpdate | null {
122
+ const headPrefix = /^ {0,3}\/head[ \t]/u;
123
+ const raw = source.text.replace(headPrefix, "");
124
+ const body = raw.trim();
125
+ const prose = transportRoutingProse(source).replace(headPrefix, "").trim();
126
+ const indented = /^[ \t]{4}|^\t/u;
127
+ const addressedText = source.discordOriginalText;
128
+ if (!body || indented.test(raw) || body !== prose || body !== ownerRoutingProse(raw) || /[\r\n??]/u.test(raw)) return null;
129
+ if (addressedText !== undefined) {
130
+ // An addressed message can be normalized by removing only the bot
131
+ // mention, but a voice draft or quoted physical line is not that prose.
132
+ const original = addressedText.replace(/<@!?(\d+)>/gu, (mention, id) => id === source.route.accountId ? " " : mention);
133
+ if (indented.test(addressedText) || /[\r\n]/u.test(addressedText)
134
+ || original.trim().replace(/\s+/gu, " ") !== source.text.trim().replace(/\s+/gu, " ")) return null;
135
+ }
136
+ const labeled = /^(?:soul|말투)\s*:\s*(\S.*)$/iu.exec(body)?.[1];
137
+ const request = labeled ?? body;
138
+ if (/^(?:please\s+)?reset(?:\s+(?:(?:the|your|our)\s+)?(?:soul|reply style|writing style))?(?:\s+to\s+(?:the\s+)?default(?:s)?)?[.!]?$/iu.test(request)
139
+ && (labeled !== undefined || /(?:soul|reply style|writing style)\b/iu.test(request))) return "reset";
140
+ if (/^(?:(?:소울|말투|응답\s*스타일)(?:을|를)?\s+)?(?:기본(?:값|값으로|으로)?\s*(?:초기화해|되돌려|돌려)|초기화(?:해)?)\s*(?:줘|주세요)?[.!]?$/u.test(request)
141
+ && (labeled !== undefined || /^(?:소울|말투|응답\s*스타일)/u.test(request))) return "reset";
142
+ const styleText = request.toLowerCase().replace(/[‘’]/gu, "'");
143
+ // A persistent change must be a direct instruction about this agent's
144
+ // replies. Questions, alternatives, scoped exceptions and examples are
145
+ // not configuration even when they contain a supported phrase.
146
+ if (/\b(?:not|don't|never|instead of|or|could|would|should|can you|if|unless|suppose|imagine|pretend|for example|example of|quote|forwarded|only when|only for|just this|(?:this|the next) (?:thread|task|reply|answer)|(?:he|she|they) (?:said|asked))\b|말고|아니[라면]|않|하지\s*마|말아|만약|가정|상상|척해|예를\s*들|예시|인용|전달받|라고\s*(?:했|하던|쓰|적)|라는\s*(?:요청|문구|말|지시)|라면|해\s*줄래|할\s*수\s*있|어떨까|어때|(?:이번|이|다음)\s*(?:한\s*번|한번|답변|작업|스레드|메시지)(?:에(?:서)?)?만|이번만/u.test(styleText)) return null;
147
+ const englishSetting = /^(?:please\s+)?(?:change|set|update)\s+(?:(?:the|your|our)\s+)?(?:soul|reply style|writing style)\b(?:\s+to)?\s+/u;
148
+ const englishReply = /^(?:please\s+)?(?:(?:answer|reply|respond|explain)\s+(?:(?:in|with|using)\s+(?:(?:a|an|the)\s+)?|(?=like\s|[a-z]+ly\b))|(?:answer|reply|respond)\s+(?=(?:answer|conclusion|result|evidence|reasoning) first\b)|use\s+(?=.*\b(?:tone|register|voice|style|length|format)\b)(?:(?:a|an|the)\s+)?)/u;
149
+ const englishFuture = /^(?:from now on|going forward|from your next reply(?: onward)?|henceforth),?\s+/u;
150
+ const koreanFuture = /^(?:(?:답변은|응답은|말투는)\s+)?(?:앞으로(?:는|도)?|이제부터(?:는)?|지금부터(?:는)?|다음(?:\s*답변)?부터(?:는)?|앞으론|항상|매번)\s+/u;
151
+ const koreanSetting = /^(?:기본\s*)?(?:소울|말투|(?:답변|응답)\s*(?:방식|스타일|말투)|답변\s*컨셉)(?:을|를|은|는)?\s+/u;
152
+ const koreanSetRequest = /(?:바꿔|변경해|설정해|정해)\s*(?:줘|주세요|주라)?[.!]?$/u;
153
+ const koreanReply = /(?:해\s*(?:줘|주세요|주라)?|알려\s*(?:줘|주세요|주라)|부탁(?:해|드려요)?)[.!]?$/u;
154
+ const koreanLead = /^(?:(?:제게|저한테|나한테|뭐든|기본적으로|답변은|응답은|말투는|답변을|응답을|말투를|답변할\s*때(?:는|마다)?|응답할\s*때(?:는|마다)?|유능한|능숙한|좋은|친절한|믿음직한)\s+)*/u;
155
+ const persistentEnglish = styleText.replace(englishFuture, "");
156
+ const persistentKorean = styleText.replace(koreanFuture, "");
157
+ let presentation: string;
158
+ if (labeled !== undefined) presentation = styleText.replace(koreanLead, "");
159
+ else if (englishSetting.test(styleText)) presentation = styleText.replace(englishSetting, "");
160
+ else if (koreanSetting.test(styleText) && koreanSetRequest.test(styleText)) presentation = styleText.replace(koreanSetting, "").replace(koreanLead, "");
161
+ else if (persistentEnglish !== styleText && englishReply.test(persistentEnglish)) presentation = persistentEnglish.replace(englishReply, "");
162
+ else if (persistentKorean !== styleText && koreanReply.test(persistentKorean)) presentation = persistentKorean.replace(koreanLead, "");
163
+ else return null;
164
+ if (labeled === undefined && !startsWithPresentation(presentation)) return null;
165
+ const patch: Record<string, string> = {};
166
+ let remainder = presentation;
167
+ for (const [dimension, choices] of Object.entries(requests)) {
168
+ const matches = Object.entries(choices).filter(([, pattern]) => pattern.test(presentation));
169
+ if (matches.length > 1) return null;
170
+ if (matches[0]) {
171
+ const [choice, pattern] = matches[0];
172
+ patch[dimension] = choice;
173
+ remainder = remainder.replace(new RegExp(pattern.source, "gu"), " ");
174
+ }
175
+ }
176
+ // Do not silently apply only the familiar half of a concept plus style
177
+ // request when the owner named an unsupported concept.
178
+ if (!patch.concept && /\b(?:concept|persona|like an?)\b|컨셉|콘셉트?|처럼|같은\s*느낌/u.test(presentation)) return null;
179
+ return onlyPresentationGrammar(remainder) && voicePatch(patch) ? patch : null;
180
+ }
181
+
182
+ export function soulSourceId(value: unknown): string {
183
+ if (object(value) && Object.keys(value).length === 1 && typeof value.sourceId === "string" && value.sourceId.trim())
184
+ return value.sourceId;
185
+ throw new Error("A reply voice update takes only its original sourceId");
186
+ }
187
+
188
+ export function applySoulUpdate(store: Ledger, sourceId: string, update: SoulUpdate) {
189
+ const current = savedVoice(store);
190
+ if (current.sourceId !== sourceId) {
191
+ const style = update === "reset" ? defaultVoice : { ...current.style, ...update };
192
+ const next = { revision: current.revision + 1, sourceId, style };
193
+ if (!Number.isSafeInteger(next.revision)) throw new Error("Reply voice revision is unavailable");
194
+ store.setMeta(setting, JSON.stringify(next));
195
+ }
196
+ const applied = savedVoice(store);
197
+ return { revision: applied.revision, style: applied.style };
198
+ }
199
+
200
+ export function replyVoiceProfile(store: Ledger, version: 1 | 2 = 2) {
201
+ const { concept, ...base } = savedVoice(store).style;
202
+ return version === 2 ? { ...base, concept } : base;
203
+ }
204
+
205
+ export function renderReplyVoice(value: unknown): string {
206
+ const style = completeVoice(value);
207
+ return [
208
+ "<superagent-reply-voice>",
209
+ "Apply this voice only to prose addressed to the operator. Use their language. Separate verified facts from inference. Task formats, role instructions, permissions and workflows are unchanged.",
210
+ dimensions.concept[style.concept], dimensions.tone[style.tone], dimensions.register[style.register], dimensions.detail[style.detail],
211
+ dimensions.structure[style.structure], dimensions.emoji[style.emoji],
212
+ "</superagent-reply-voice>",
213
+ ].filter(Boolean).join("\n");
214
+ }