omp-superagent 0.0.0-stage → 0.1.1

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 (76) hide show
  1. package/DESIGN.md +1361 -0
  2. package/LICENSE +21 -0
  3. package/README.ko.md +184 -0
  4. package/README.md +205 -2
  5. package/THIRD_PARTY_NOTICES.md +313 -0
  6. package/assets/architecture.mmd +24 -0
  7. package/assets/architecture.svg +126 -0
  8. package/assets/superagent-avatar.jpg +0 -0
  9. package/assets/superagent-mascot.webp +0 -0
  10. package/config.example.json +26 -0
  11. package/docs/OPERATIONS.md +1030 -0
  12. package/docs/releases/0.1.0.md +222 -0
  13. package/docs/releases/0.1.1.md +60 -0
  14. package/package.json +59 -4
  15. package/scripts/check-omp.ts +4 -0
  16. package/scripts/ci.ts +28 -0
  17. package/scripts/prepare-ulw.ts +18 -0
  18. package/scripts/release.ts +50 -0
  19. package/scripts/setup.sh +25 -0
  20. package/skills/head/SKILL.md +259 -0
  21. package/skills/head/references/model-selection.md +263 -0
  22. package/skills/head/references/routing.md +356 -0
  23. package/skills/head/references/supervision.md +312 -0
  24. package/skills/lane/SKILL.md +188 -0
  25. package/skills/lane/references/workflow.md +349 -0
  26. package/src/autostart.ts +295 -0
  27. package/src/board-extension.ts +217 -0
  28. package/src/board.ts +396 -0
  29. package/src/cli.ts +167 -0
  30. package/src/config.ts +191 -0
  31. package/src/contracts.ts +317 -0
  32. package/src/credentials.ts +172 -0
  33. package/src/delivery.ts +7 -0
  34. package/src/dialog.ts +73 -0
  35. package/src/discord-command-registration.ts +201 -0
  36. package/src/discord-commands.ts +29 -0
  37. package/src/discord-markdown.ts +172 -0
  38. package/src/discord.ts +745 -0
  39. package/src/extension.ts +289 -0
  40. package/src/gateway-client.ts +222 -0
  41. package/src/gateway-protocol.ts +85 -0
  42. package/src/gateway-restart.ts +151 -0
  43. package/src/gateway-server.ts +392 -0
  44. package/src/gateway-store.ts +237 -0
  45. package/src/gateway.ts +638 -0
  46. package/src/head-recovery.ts +61 -0
  47. package/src/host-extension.ts +449 -0
  48. package/src/host-owner.ts +350 -0
  49. package/src/host-protocol.ts +136 -0
  50. package/src/host.ts +414 -0
  51. package/src/installed-omp.ts +63 -0
  52. package/src/lane-extension.ts +179 -0
  53. package/src/lane-models.ts +75 -0
  54. package/src/lane-report.ts +70 -0
  55. package/src/managed-ulw-probe.ts +172 -0
  56. package/src/managed-ulw.ts +471 -0
  57. package/src/message-order.ts +21 -0
  58. package/src/messenger-commands.ts +16 -0
  59. package/src/messengers.ts +114 -0
  60. package/src/native-presets.ts +282 -0
  61. package/src/native-sessions.ts +32 -0
  62. package/src/native-settings.ts +129 -0
  63. package/src/repository.ts +12 -0
  64. package/src/runtime.ts +3864 -0
  65. package/src/setup-judge.ts +34 -0
  66. package/src/setup-memory.ts +39 -0
  67. package/src/setup-profiles.ts +84 -0
  68. package/src/setup.ts +300 -0
  69. package/src/slack-command-registration.ts +217 -0
  70. package/src/slack-commands.ts +18 -0
  71. package/src/slack.ts +776 -0
  72. package/src/store.ts +806 -0
  73. package/src/telegram-command-registration.ts +155 -0
  74. package/src/telegram.ts +661 -0
  75. package/src/workflow.ts +94 -0
  76. package/upstream/ulw.json +9 -0
@@ -0,0 +1,75 @@
1
+ import type { LaneModel, LaneModelChoice, ModelPreset, LanePresetSnapshot, ResolvedLanePreset } from "./contracts";
2
+
3
+ export interface LaneModelCandidate extends LaneModel {
4
+ name?: string;
5
+ input?: string[];
6
+ contextWindow?: number;
7
+ maxTokens?: number;
8
+ reasoning?: boolean;
9
+ supportsTools?: boolean;
10
+ cost?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number };
11
+ }
12
+
13
+ export function sameLaneModel(left: LaneModel | null | undefined, right: LaneModel | null | undefined): boolean {
14
+ return !!left && !!right && left.provider === right.provider && left.id === right.id;
15
+ }
16
+
17
+ export function isLaneModel(value: unknown): value is LaneModel {
18
+ if (!value || typeof value !== "object") return false;
19
+ const model = value as Record<string, unknown>;
20
+ return typeof model.provider === "string" && !!model.provider.trim() && !model.provider.includes("\0") &&
21
+ typeof model.id === "string" && !!model.id.trim() && !model.id.includes("\0");
22
+ }
23
+
24
+ /** Project native catalog facts only: endpoints, headers, credentials and opaque internals never leave here. */
25
+ export function codingModels(value: unknown): LaneModelCandidate[] {
26
+ if (!Array.isArray(value)) throw new Error("Native available-model response is missing its model list");
27
+ const candidates = new Map<string, LaneModelCandidate>();
28
+ for (const entry of value) {
29
+ if (!isLaneModel(entry)) continue;
30
+ const native = entry as LaneModel & Record<string, unknown>;
31
+ // Native Model.kind is optional; omission means ordinary chat. Judge/tiny and
32
+ // other specialized runners are not coding-session model choices.
33
+ if (native.kind !== undefined && native.kind !== "chat") continue;
34
+ const model: LaneModelCandidate = { provider: entry.provider, id: entry.id };
35
+ if (typeof native.name === "string") model.name = native.name;
36
+ if (Array.isArray(native.input) && native.input.every(item => typeof item === "string")) model.input = [...native.input];
37
+ if (typeof native.contextWindow === "number" && Number.isFinite(native.contextWindow) && native.contextWindow > 0) model.contextWindow = native.contextWindow;
38
+ if (typeof native.maxTokens === "number" && Number.isFinite(native.maxTokens) && native.maxTokens > 0) model.maxTokens = native.maxTokens;
39
+ if (typeof native.reasoning === "boolean") model.reasoning = native.reasoning;
40
+ if (typeof native.supportsTools === "boolean") model.supportsTools = native.supportsTools;
41
+ if (native.cost && typeof native.cost === "object") {
42
+ const costs = native.cost as Record<string, unknown>;
43
+ const cost: NonNullable<LaneModelCandidate["cost"]> = {};
44
+ for (const key of ["input", "output", "cacheRead", "cacheWrite"] as const) {
45
+ const amount = costs[key];
46
+ if (typeof amount === "number" && Number.isFinite(amount) && amount >= 0) cost[key] = amount;
47
+ }
48
+ if (Object.keys(cost).length) model.cost = cost;
49
+ }
50
+ candidates.set(JSON.stringify([model.provider, model.id]), model);
51
+ }
52
+ return [...candidates.values()];
53
+ }
54
+
55
+ export function laneModelArgument(model: LaneModel): string {
56
+ if (!isLaneModel(model)) throw new Error("Lane model requires an exact provider and model ID");
57
+ return `${model.provider}/${model.id}`;
58
+ }
59
+
60
+ export async function resolveLaneModelChoice(
61
+ choice: LaneModelChoice,
62
+ resolvePreset?: (name: ModelPreset) => Promise<ResolvedLanePreset>,
63
+ ): Promise<{ model: LaneModel; preset: ModelPreset | null; snapshot: LanePresetSnapshot | null }> {
64
+ if ((choice.model !== undefined) === (choice.preset !== undefined))
65
+ throw new Error("Choose exactly one lane model or native OMP preset");
66
+ if (choice.preset !== undefined) {
67
+ if (!resolvePreset) throw new Error("Native OMP preset resolution is unavailable");
68
+ const resolved = await resolvePreset(choice.preset);
69
+ if (resolved.preset !== choice.preset || !isLaneModel(resolved.model))
70
+ throw new Error("Native OMP preset resolution returned a mismatched identity");
71
+ return { model: { ...resolved.model }, preset: resolved.preset, snapshot: structuredClone(resolved.snapshot) };
72
+ }
73
+ if (!isLaneModel(choice.model)) throw new Error("Lane model requires an exact provider and model ID");
74
+ return { model: { provider: choice.model.provider, id: choice.model.id }, preset: null, snapshot: null };
75
+ }
@@ -0,0 +1,70 @@
1
+ import { isAbsolute, normalize } from "node:path";
2
+
3
+ export type LaneWaitTarget =
4
+ | { kind: "tool" | "approval" | "job"; id: string; target: string }
5
+ | { kind: "dependency"; target: string };
6
+
7
+ export interface LaneEvidence {
8
+ kind: "file" | "tool";
9
+ ref: string;
10
+ fingerprint: string;
11
+ }
12
+
13
+ export interface LaneReport {
14
+ status: "progress" | "waiting" | "resolved";
15
+ summary: string;
16
+ evidence: LaneEvidence[];
17
+ waiting?: LaneWaitTarget;
18
+ }
19
+
20
+ export interface LaneReportEvent {
21
+ type: "superagent-lane-report";
22
+ sessionId: string;
23
+ reportId: string;
24
+ report: LaneReport;
25
+ }
26
+
27
+ export function laneWaitKey(waiting: LaneWaitTarget): string {
28
+ return JSON.stringify([waiting.kind, waiting.kind === "dependency" ? waiting.target : waiting.id]);
29
+ }
30
+
31
+ const record = (value: unknown): value is Record<string, unknown> =>
32
+ value !== null && typeof value === "object" && !Array.isArray(value);
33
+ const text = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0;
34
+ const keys = (value: Record<string, unknown>, names: string[]) =>
35
+ Object.keys(value).every(key => names.includes(key));
36
+
37
+ /** Parse only the structured native result, never receipt text or a claimed event in content. */
38
+ export function parseLaneReportResult(result: unknown): LaneReportEvent | null {
39
+ try {
40
+ if (!record(result) || result.isError === true || !record(result.details)) return null;
41
+ const event = result.details;
42
+ if (!keys(event, ["type", "sessionId", "reportId", "report"]) ||
43
+ event.type !== "superagent-lane-report" || !text(event.sessionId) || !text(event.reportId) ||
44
+ !record(event.report)) return null;
45
+ const report = event.report;
46
+ if (!keys(report, ["status", "summary", "evidence", "waiting"]) ||
47
+ !["progress", "waiting", "resolved"].includes(report.status as string) ||
48
+ !text(report.summary) || report.summary.length > 4000 || !Array.isArray(report.evidence) ||
49
+ report.evidence.length > 32) return null;
50
+ if (report.evidence.some(item => !record(item) || !keys(item, ["kind", "ref", "fingerprint"]) ||
51
+ (item.kind !== "file" && item.kind !== "tool") || !text(item.ref) ||
52
+ (item.kind === "file" && (!isAbsolute(item.ref) || normalize(item.ref) !== item.ref)) ||
53
+ typeof item.fingerprint !== "string" || !/^[a-f0-9]{64}$/.test(item.fingerprint))) return null;
54
+ if (report.status !== "waiting" && report.evidence.length === 0) return null;
55
+ if (report.status === "progress") {
56
+ if (Object.hasOwn(report, "waiting")) return null;
57
+ } else {
58
+ const waiting = report.waiting;
59
+ if (!record(waiting) || !text(waiting.target)) return null;
60
+ if (waiting.kind === "dependency") {
61
+ if (!keys(waiting, ["kind", "target"])) return null;
62
+ } else if (!["tool", "approval", "job"].includes(waiting.kind as string) ||
63
+ !text(waiting.id) || !keys(waiting, ["kind", "id", "target"])) return null;
64
+ }
65
+ return event as unknown as LaneReportEvent;
66
+ } catch {
67
+ // Malformed native details must not escape into the head's event loop.
68
+ return null;
69
+ }
70
+ }
@@ -0,0 +1,172 @@
1
+ // Finite native prompt-composition gate, not a model turn or workflow execution.
2
+ import assert from "node:assert/strict";
3
+ import { mkdir, readFile, realpath } from "node:fs/promises";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { getBundledModel, getBundledProviders } from "@oh-my-pi/pi-catalog";
6
+ import { ModelRegistry, Settings, AuthStorage, SessionManager, createAgentSession } from "@oh-my-pi/pi-coding-agent";
7
+ import { ExtensionRunner } from "@oh-my-pi/pi-coding-agent/extensibility/extensions/runner";
8
+ import { listPackageExtensionModules, loadExtensions } from "@oh-my-pi/pi-coding-agent/extensibility/extensions/loader";
9
+ import { buildSystemPrompt } from "@oh-my-pi/pi-coding-agent/system-prompt";
10
+
11
+ const packagePath = process.argv[2];
12
+ if (!packagePath) throw new Error("Managed ULW probe requires a package path");
13
+ const home = process.env.HOME;
14
+ const agentDir = process.env.PI_CODING_AGENT_DIR;
15
+ assert(home && agentDir && resolve(dirname(agentDir)) === resolve(home) && resolve(process.cwd()) === resolve(home),
16
+ "Managed ULW probe requires the updater's isolated HOME, agent directory and working directory");
17
+ let networkAttempts = 0;
18
+ const refuseNetwork = () => { networkAttempts++; throw new Error("Managed ULW probe forbids network and provider calls"); };
19
+ globalThis.fetch = Object.assign(async () => refuseNetwork(), { preconnect: refuseNetwork });
20
+
21
+ const modules = await listPackageExtensionModules([packagePath], process.cwd(), { plugins: false });
22
+ if (!modules.length) throw new Error("Managed ULW has no discoverable extension");
23
+ // Use the same supported identity as the native composition fixture, but take
24
+ // every model field from the declared published catalog rather than inventing a provider.
25
+ const model = getBundledModel("xai", "grok-4.5");
26
+ assert(model, "Pinned OMP catalog is missing the native composition model xai/grok-4.5");
27
+ await mkdir(agentDir, { recursive: true, mode: 0o700 });
28
+ const settings = await Settings.loadIsolated({
29
+ cwd: home, agentDir, inMemory: true,
30
+ overrides: {
31
+ disabledProviders: [...new Set([...getBundledProviders(), "ollama", "lm-studio", "llama.cpp", "apple"])],
32
+ "memory.backend": "off", "autolearn.enabled": false,
33
+ },
34
+ });
35
+ const authStorage = await AuthStorage.create(":memory:");
36
+ try {
37
+ const sessionManager = SessionManager.inMemory(home);
38
+ const loaded = await loadExtensions(modules.map(module => module.path), home);
39
+ assert.deepEqual(loaded.errors, [], "Native OMP rejected managed ULW");
40
+ assert.equal(loaded.extensions.length, modules.length, "Native OMP must load every advertised extension");
41
+ // Render the published SDK's bundled template in the isolated HOME without
42
+ // tools, memory backend, SDK Agent, services, or provider/model execution.
43
+ const { systemPrompt: nativeBase } = await buildSystemPrompt({
44
+ cwd: home, model: `${model.provider}/${model.id}`,
45
+ contextFiles: [], noContextFiles: true, rules: [], skills: [],
46
+ toolNames: [], activeRepoContext: null, personality: "none",
47
+ });
48
+ const runner = new ExtensionRunner(loaded.extensions, loaded.runtime, home, sessionManager,
49
+ new ModelRegistry(authStorage, join(home, "models.yml"), { settings }), undefined, settings);
50
+ const errors: unknown[] = [];
51
+ const refuseEffect = (): never => {
52
+ const error = new Error("Managed ULW prompt probe forbids agent, tool, service and session-control effects");
53
+ errors.push(error);
54
+ throw error;
55
+ };
56
+ let currentSystemPrompt = nativeBase;
57
+ // This is a prompt-only host, not a fake agent: only in-memory journal writes
58
+ // and read-only context exist. Unsupported effects fail the activation gate.
59
+ runner.initialize({
60
+ sendMessage: refuseEffect, sendUserMessage: refuseEffect,
61
+ appendEntry: (customType, data) => { sessionManager.appendCustomEntry(customType, data); },
62
+ setLabel: (targetId, label) => { sessionManager.appendLabelChange(targetId, label); },
63
+ getActiveTools: () => [], getAllTools: () => [], setActiveTools: refuseEffect,
64
+ getCommands: refuseEffect, setModel: refuseEffect,
65
+ getThinkingLevel: () => undefined, setThinkingLevel: refuseEffect,
66
+ getServiceTiers: () => ({}), setServiceTier: refuseEffect,
67
+ getSessionName: () => sessionManager.getSessionName(), setSessionName: refuseEffect,
68
+ }, {
69
+ getModel: () => model, isIdle: () => true, hasPendingMessages: () => false,
70
+ abort: refuseEffect, shutdown: refuseEffect, compact: refuseEffect,
71
+ getContextUsage: () => undefined, getSystemPrompt: () => currentSystemPrompt,
72
+ runEphemeralTurn: refuseEffect, startLive: refuseEffect,
73
+ });
74
+ runner.onError(error => { errors.push(error); });
75
+ try {
76
+ await runner.emit({ type: "session_start" });
77
+ assert(nativeBase[0] && nativeBase[0].length > 500, "Probe must use OMP's actual rendered native prompt");
78
+ const nativeRole = /(?:^|\n[§⁂] Role\n)([\s\S]*?)\n[§⁂] Runtime\n/.exec(nativeBase[0])?.[1];
79
+ assert(nativeRole && nativeRole.trim(), "Native prompt has no recognizable role to replace");
80
+ const initialBranch = structuredClone(sessionManager.getBranch());
81
+ const occurrences = (text: string, needle: string) => text.split(needle).length - 1;
82
+ const check = (blocks: string[], workflow: boolean) => {
83
+ const text = blocks.join("\n\n");
84
+ assert.equal(occurrences(text, "<omp-model-preset>"), 1, "Expected exactly one applied model preset");
85
+ assert.equal(occurrences(text, "</omp-model-preset>"), 1, "Expected one complete model preset");
86
+ const preset = /<omp-model-preset>([\s\S]*?)<\/omp-model-preset>/.exec(text)?.[1];
87
+ assert(preset && preset.trim().length > 200, "Model preset must contain working instructions, not an empty marker");
88
+ assert.match(preset, /Grok 4\.5/, "Supported model-specific instructions must actually be selected");
89
+ assert(!text.includes(nativeRole), "Model preset did not replace the native role");
90
+ assert.equal(occurrences(text, "<omp-ulw-policy>"), workflow ? 1 : 0,
91
+ workflow ? "Expected exactly one explicitly activated ULW policy" : "Model-profile loading must not activate ULW");
92
+ assert.equal(occurrences(text, "</omp-ulw-policy>"), workflow ? 1 : 0);
93
+ if (workflow) {
94
+ const policy = /<omp-ulw-policy>\s*<ultrawork-mode>([\s\S]*?)<\/ultrawork-mode>\s*<\/omp-ulw-policy>/.exec(text)?.[1];
95
+ assert(policy && policy.trim().length > 200, "Activated ULW policy must contain the workflow directive");
96
+ assert(!nativeBase.join("\n\n").includes(policy), "Workflow policy must come from the candidate hook");
97
+ }
98
+ assert.deepEqual(errors, [], "Managed ULW native hooks failed");
99
+ assert.equal(networkAttempts, 0);
100
+ };
101
+ const compose = async (prompt: string, base: string[], workflow: boolean) => {
102
+ currentSystemPrompt = [...base];
103
+ const result = await runner.emitBeforeAgentStart(prompt, undefined, [...base]);
104
+ const blocks = result?.systemPrompt ?? base;
105
+ currentSystemPrompt = blocks;
106
+ check(blocks, workflow);
107
+ return blocks;
108
+ };
109
+ // Fresh turns and recomposition must both retain exactly one preset. No
110
+ // input event, command handler, session.prompt(), provider, or goal executes.
111
+ const ordinary = "Inspect the requested implementation and report evidence.";
112
+ for (let turn = 0; turn < 2; turn++) {
113
+ await compose(ordinary, await compose(ordinary, nativeBase, false), false);
114
+ }
115
+ assert.deepEqual(sessionManager.getBranch(), initialBranch, "Ordinary profile loading must not arm workflow state");
116
+ const activated = `ulw ${ordinary}`;
117
+ for (let turn = 0; turn < 2; turn++) {
118
+ await compose(activated, await compose(activated, nativeBase, true), true);
119
+ }
120
+ assert(sessionManager.getBranch().every(entry => entry.type !== "message"),
121
+ "Workflow activation inspection must not create user/model messages");
122
+ // An independent, unstarted SDK session proves native tools and skill://
123
+ // resources without input, MCP/LSP, Python preflight, or a provider turn.
124
+ const { session: resources, extensionsResult } = await createAgentSession({
125
+ cwd: home, agentDir, settings, authStorage,
126
+ modelRegistry: new ModelRegistry(authStorage, join(home, "models.yml"), { settings }),
127
+ model, sessionManager: SessionManager.inMemory(home),
128
+ additionalExtensionPaths: [packagePath], disableExtensionDiscovery: true,
129
+ contextFiles: [], rules: [], promptTemplates: [], slashCommands: [],
130
+ preloadedCustomToolPaths: [], toolNames: ["read", "task"],
131
+ enableMCP: false, enableLsp: false, skipPythonPreflight: true,
132
+ });
133
+ const resourceReads: string[] = [];
134
+ try {
135
+ assert.deepEqual(extensionsResult.errors, [], "Published SDK rejected managed ULW resources");
136
+ assert.deepEqual(extensionsResult.extensions.filter(extension => !extension.path.startsWith("<inline-"))
137
+ .map(extension => extension.resolvedPath), loaded.extensions.map(extension => extension.resolvedPath),
138
+ "Resource inspection must load exactly the candidate modules, apart from SDK-owned inline factories");
139
+ assert(resources.getEnabledToolNames().includes("read"), "Native read must remain available");
140
+ assert(resources.getEnabledToolNames().includes("task"), "Native task must remain available");
141
+ const root = await realpath(packagePath);
142
+ const skills = resources.skills.filter(skill => skill.filePath.startsWith(root + "/"));
143
+ assert(skills.length, "Managed ULW must expose its actual skills through native discovery");
144
+ const read = resources.getToolByName("read")!;
145
+ for (const skill of skills) {
146
+ const uri = `skill://${skill.name}:raw`;
147
+ const output = await read.execute(`managed-ulw-resource-${resourceReads.length}`, { path: uri });
148
+ const text = output.content.flatMap(block => block.type === "text" ? [block.text] : []).join("\n");
149
+ assert.equal(text, await readFile(skill.filePath, "utf8"), `Native resource differs from ${skill.filePath}`);
150
+ resourceReads.push(uri);
151
+ }
152
+ assert.equal(resources.isStreaming, false);
153
+ assert(!resources.sessionManager.getBranch().some(entry => entry.type === "message"),
154
+ "Resource inspection must not activate a model turn");
155
+ assert.equal(networkAttempts, 0);
156
+ } finally { await resources.dispose(); }
157
+ console.log(JSON.stringify({ extensions: loaded.extensions.length,
158
+ compatibility: "published-sdk-prompt-composition", model: `${model.provider}/${model.id}`,
159
+ ordinaryTurns: 2, activatedTurns: 2, tools: ["read", "task"], resourceReads,
160
+ sessionPersistence: "memory", networkAttempts }));
161
+ } finally {
162
+ try {
163
+ await runner.emit({ type: "session_shutdown" });
164
+ assert.deepEqual(errors, [], "Managed ULW native hooks failed");
165
+ assert.equal(networkAttempts, 0);
166
+ } finally {
167
+ runner.clearManagedTimers();
168
+ runner.disposeFileFallbacks();
169
+ }
170
+ }
171
+ } finally { authStorage.close(); }
172
+ process.exit(0);