@geminixiang/mikan 1.0.0-beta.73 → 1.0.0-beta.74

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.
@@ -0,0 +1,34 @@
1
+ import type { MikanHarnessTool } from "../types.js";
2
+ interface SecretEntry {
3
+ /** `[SECRET:<label>]` placeholder shown in place of the value. */
4
+ label: string;
5
+ value: string;
6
+ }
7
+ /**
8
+ * Replace every occurrence of a known secret env var's value in `text` with
9
+ * `[SECRET:<VAR_NAME>]`. Safe to call on arbitrary tool output; a no-op when
10
+ * no configured secret value appears in it.
11
+ */
12
+ export declare function redactSecrets(text: string, secrets?: SecretEntry[]): string;
13
+ export type { SecretEntry };
14
+ /**
15
+ * Wrap a harness tool so every text part of its result passes through
16
+ * {@link redactSecrets} before the model or the session ever sees it. Applied
17
+ * uniformly to every tool at assembly time (`tools/index.ts`) rather than
18
+ * only `bash`: `read` can return a secret file's contents just as easily,
19
+ * and a platform or MCP tool could too.
20
+ *
21
+ * Mutates `tool.execute` in place rather than spreading into a new object.
22
+ * `pi-tools.ts`'s `isHarnessTool` marks a tool with a non-enumerable symbol
23
+ * property (`Object.defineProperty`, default `enumerable: false`), and a
24
+ * platform pack's `bindRun` closure can hold the exact tool object it wired
25
+ * up (`host-fn-tool.ts`'s `setFn`). A `{ ...tool }` spread drops that
26
+ * marker and detaches the copy from the pack's binding — which is exactly
27
+ * what happened here first: every platform/task/subagent tool silently
28
+ * stopped running because the session's `isHarnessTool` check saw an
29
+ * unmarked object and re-adapted an already-harness tool, scrambling its
30
+ * call signature. In-place mutation keeps identity, markers, and bound
31
+ * state intact; only `execute`'s behavior changes.
32
+ */
33
+ export declare function withSecretRedaction(tool: MikanHarnessTool): MikanHarnessTool;
34
+ //# sourceMappingURL=secret-redaction.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret-redaction.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/secret-redaction.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAMpD,UAAU,WAAW;IACnB,kEAAkE;IAClE,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACf;AAwBD;;;;GAIG;AACH,wBAAgB,aAAa,CAC3B,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,WAAW,EAA2B,GAC9C,MAAM,CAQR;AAED,YAAY,EAAE,WAAW,EAAE,CAAC;AAE5B;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,gBAAgB,GAAG,gBAAgB,CAc5E"}
@@ -0,0 +1,77 @@
1
+ import { ENV_MANIFEST, readEnv } from "../../env-manifest.js";
2
+ /** Values shorter than this are not redacted: too likely to false-positive
3
+ * on ordinary short strings (e.g. a placeholder, a short flag value). */
4
+ const MIN_SECRET_LENGTH = 8;
5
+ /**
6
+ * Read every `secret: true` env var's current value from the process
7
+ * environment (via `readEnv`, so a `MIKAN_`-prefixed alias counts too).
8
+ * Recomputed per call — cheap, and correctness matters more than caching a
9
+ * snapshot that could go stale relative to `process.env`.
10
+ */
11
+ function collectSecretEntries() {
12
+ const entries = [];
13
+ for (const group of ENV_MANIFEST) {
14
+ for (const spec of group.vars) {
15
+ if (!spec.secret)
16
+ continue;
17
+ const value = readEnv(spec.name);
18
+ if (!value || value.length < MIN_SECRET_LENGTH)
19
+ continue;
20
+ entries.push({ label: spec.name, value });
21
+ }
22
+ }
23
+ // Longest value first: if one secret's value is a substring of another's
24
+ // (unlikely but not impossible), replace the longer match first so the
25
+ // shorter one does not leave a partial secret behind.
26
+ return entries.toSorted((a, b) => b.value.length - a.value.length);
27
+ }
28
+ /**
29
+ * Replace every occurrence of a known secret env var's value in `text` with
30
+ * `[SECRET:<VAR_NAME>]`. Safe to call on arbitrary tool output; a no-op when
31
+ * no configured secret value appears in it.
32
+ */
33
+ export function redactSecrets(text, secrets = collectSecretEntries()) {
34
+ if (!text || secrets.length === 0)
35
+ return text;
36
+ let result = text;
37
+ for (const { label, value } of secrets) {
38
+ if (!result.includes(value))
39
+ continue;
40
+ result = result.split(value).join(`[SECRET:${label}]`);
41
+ }
42
+ return result;
43
+ }
44
+ /**
45
+ * Wrap a harness tool so every text part of its result passes through
46
+ * {@link redactSecrets} before the model or the session ever sees it. Applied
47
+ * uniformly to every tool at assembly time (`tools/index.ts`) rather than
48
+ * only `bash`: `read` can return a secret file's contents just as easily,
49
+ * and a platform or MCP tool could too.
50
+ *
51
+ * Mutates `tool.execute` in place rather than spreading into a new object.
52
+ * `pi-tools.ts`'s `isHarnessTool` marks a tool with a non-enumerable symbol
53
+ * property (`Object.defineProperty`, default `enumerable: false`), and a
54
+ * platform pack's `bindRun` closure can hold the exact tool object it wired
55
+ * up (`host-fn-tool.ts`'s `setFn`). A `{ ...tool }` spread drops that
56
+ * marker and detaches the copy from the pack's binding — which is exactly
57
+ * what happened here first: every platform/task/subagent tool silently
58
+ * stopped running because the session's `isHarnessTool` check saw an
59
+ * unmarked object and re-adapted an already-harness tool, scrambling its
60
+ * call signature. In-place mutation keeps identity, markers, and bound
61
+ * state intact; only `execute`'s behavior changes.
62
+ */
63
+ export function withSecretRedaction(tool) {
64
+ const original = tool.execute.bind(tool);
65
+ tool.execute = async (...args) => {
66
+ const result = await original(...args);
67
+ const secrets = collectSecretEntries();
68
+ if (secrets.length === 0)
69
+ return result;
70
+ return {
71
+ ...result,
72
+ content: result.content.map((part) => part.type === "text" ? { ...part, text: redactSecrets(part.text, secrets) } : part),
73
+ };
74
+ };
75
+ return tool;
76
+ }
77
+ //# sourceMappingURL=secret-redaction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret-redaction.js","sourceRoot":"","sources":["../../../src/harness/tools/secret-redaction.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAG9D;0EAC0E;AAC1E,MAAM,iBAAiB,GAAG,CA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;;;;;;;;GAkBG;AACH,MAAM,UAAU,mBAAmB,CAAC,IAAsB;IACxD,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACzC,IAAI,CAAC,OAAO,GAAG,KAAK,EAAE,GAAG,IAA6C,EAAE,EAAE;QACxE,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,GAAG,IAAI,CAAC,CAAC;QACvC,MAAM,OAAO,GAAG,oBAAoB,EAAE,CAAC;QACvC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,MAAM,CAAC;QACxC,OAAO;YACL,GAAG,MAAM;YACT,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,EAA8B,EAAE,CAC/D,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,IAAI,EAAE,aAAa,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CACnF;SACF,CAAC;IACJ,CAAC,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * Redacts secret env var values out of tool output before it reaches the\n * model or gets persisted in the session transcript.\n *\n * mikan does not sandbox-isolate environment variables in host sandbox mode\n * (`docs/testing/slack-e2e.md`, `AGENTS.md`: host sandbox is trusted, not OS\n * isolation), so a tool that runs a shell command or reads a file can expose\n * any secret value the mikan process itself holds — `echo $OPENROUTER_API_KEY`\n * or `cat .env` return it in plain text. Without this pass, that plain text\n * flows straight into the model's context and the durable session JSONL; the\n * only remaining defense was the model choosing not to repeat it, which is\n * not a defense the model can be trusted to hold up. This is defense in\n * depth, not the sole one: authorized tools should still avoid emitting\n * secrets in the first place.\n *\n * `ENV_MANIFEST` is mikan's own inventory of every env var it reads, with\n * `secret: true` already curated (used today by `mikan env`'s report). This\n * module is the second consumer of that same authority, not a parallel list\n * that could drift from it.\n */\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai\";\nimport { ENV_MANIFEST, readEnv } from \"../../env-manifest.js\";\nimport type { MikanHarnessTool } from \"../types.js\";\n\n/** Values shorter than this are not redacted: too likely to false-positive\n * on ordinary short strings (e.g. a placeholder, a short flag value). */\nconst MIN_SECRET_LENGTH = 8;\n\ninterface SecretEntry {\n /** `[SECRET:<label>]` placeholder shown in place of the value. */\n label: string;\n value: string;\n}\n\n/**\n * Read every `secret: true` env var's current value from the process\n * environment (via `readEnv`, so a `MIKAN_`-prefixed alias counts too).\n * Recomputed per call — cheap, and correctness matters more than caching a\n * snapshot that could go stale relative to `process.env`.\n */\nfunction collectSecretEntries(): SecretEntry[] {\n const entries: SecretEntry[] = [];\n for (const group of ENV_MANIFEST) {\n for (const spec of group.vars) {\n if (!spec.secret) continue;\n const value = readEnv(spec.name);\n if (!value || value.length < MIN_SECRET_LENGTH) continue;\n entries.push({ label: spec.name, value });\n }\n }\n // Longest value first: if one secret's value is a substring of another's\n // (unlikely but not impossible), replace the longer match first so the\n // shorter one does not leave a partial secret behind.\n return entries.toSorted((a, b) => b.value.length - a.value.length);\n}\n\n/**\n * Replace every occurrence of a known secret env var's value in `text` with\n * `[SECRET:<VAR_NAME>]`. Safe to call on arbitrary tool output; a no-op when\n * no configured secret value appears in it.\n */\nexport function redactSecrets(\n text: string,\n secrets: SecretEntry[] = collectSecretEntries(),\n): string {\n if (!text || secrets.length === 0) return text;\n let result = text;\n for (const { label, value } of secrets) {\n if (!result.includes(value)) continue;\n result = result.split(value).join(`[SECRET:${label}]`);\n }\n return result;\n}\n\nexport type { SecretEntry };\n\n/**\n * Wrap a harness tool so every text part of its result passes through\n * {@link redactSecrets} before the model or the session ever sees it. Applied\n * uniformly to every tool at assembly time (`tools/index.ts`) rather than\n * only `bash`: `read` can return a secret file's contents just as easily,\n * and a platform or MCP tool could too.\n *\n * Mutates `tool.execute` in place rather than spreading into a new object.\n * `pi-tools.ts`'s `isHarnessTool` marks a tool with a non-enumerable symbol\n * property (`Object.defineProperty`, default `enumerable: false`), and a\n * platform pack's `bindRun` closure can hold the exact tool object it wired\n * up (`host-fn-tool.ts`'s `setFn`). A `{ ...tool }` spread drops that\n * marker and detaches the copy from the pack's binding — which is exactly\n * what happened here first: every platform/task/subagent tool silently\n * stopped running because the session's `isHarnessTool` check saw an\n * unmarked object and re-adapted an already-harness tool, scrambling its\n * call signature. In-place mutation keeps identity, markers, and bound\n * state intact; only `execute`'s behavior changes.\n */\nexport function withSecretRedaction(tool: MikanHarnessTool): MikanHarnessTool {\n const original = tool.execute.bind(tool);\n tool.execute = async (...args: Parameters<MikanHarnessTool[\"execute\"]>) => {\n const result = await original(...args);\n const secrets = collectSecretEntries();\n if (secrets.length === 0) return result;\n return {\n ...result,\n content: result.content.map((part): TextContent | ImageContent =>\n part.type === \"text\" ? { ...part, text: redactSecrets(part.text, secrets) } : part,\n ),\n };\n };\n return tool;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"conversation-runtime.d.ts","sourceRoot":"","sources":["../../src/runtime/conversation-runtime.ts"],"names":[],"mappings":"AAyDA,YAAY,EACV,iBAAiB,EACjB,mBAAmB,EACnB,0BAA0B,GAC3B,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAEV,mBAAmB,EACnB,0BAA0B,EAE3B,MAAM,YAAY,CAAC;AAsDpB,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,0BAA0B,GAClC,mBAAmB,CAErB"}
1
+ {"version":3,"file":"conversation-runtime.d.ts","sourceRoot":"","sources":["../../src/runtime/conversation-runtime.ts"],"names":[],"mappings":"AAyDA,YAAY,EACV,iBAAiB,EACjB,mBAAmB,EACnB,0BAA0B,GAC3B,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAEV,mBAAmB,EACnB,0BAA0B,EAE3B,MAAM,YAAY,CAAC;AA2DpB,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,0BAA0B,GAClC,mBAAmB,CAErB"}
@@ -38,18 +38,21 @@ function requestStop(state) {
38
38
  async function postAbortNotice(state, bot, conversationId, platformName) {
39
39
  if (state.shutdownAborted) {
40
40
  recordCounter("agent.run.shutdown_aborted", 1, { platform: platformName });
41
- await bot.postMessage(conversationId, formatRestarting(bot));
41
+ const text = formatRestarting(bot);
42
+ const ts = await bot.postMessage(conversationId, text);
43
+ bot.logBotResponse?.(conversationId, text, ts);
42
44
  return;
43
45
  }
44
46
  if (!state.stopRequested)
45
47
  return;
46
48
  if (state.stopNoticeOwned)
47
49
  return;
48
- const thread = threadSuffixOf(state.sessionKey);
49
- if (thread && bot.postInThread)
50
- await bot.postInThread(conversationId, thread, formatStopped(bot));
51
- else
52
- await bot.postMessage(conversationId, formatStopped(bot));
50
+ const thread = threadSuffixOf(state.sessionKey) ?? undefined;
51
+ const text = formatStopped(bot);
52
+ const ts = thread && bot.postInThread
53
+ ? await bot.postInThread(conversationId, thread, text)
54
+ : await bot.postMessage(conversationId, text);
55
+ bot.logBotResponse?.(conversationId, text, ts, thread);
53
56
  }
54
57
  export function createConversationRuntime(options) {
55
58
  return new ConversationRuntimeImpl(options);
@@ -112,9 +115,13 @@ class ConversationRuntimeImpl {
112
115
  }
113
116
  async handleStop(address, sessionKey, bot, replyThreadTs) {
114
117
  assertSessionKeyBelongsToConversation(sessionKey, address.conversationId);
115
- const post = (text) => replyThreadTs && bot.postInThread
116
- ? bot.postInThread(address.conversationId, replyThreadTs, text)
117
- : bot.postMessage(address.conversationId, text);
118
+ const post = async (text) => {
119
+ const ts = replyThreadTs && bot.postInThread
120
+ ? await bot.postInThread(address.conversationId, replyThreadTs, text)
121
+ : await bot.postMessage(address.conversationId, text);
122
+ bot.logBotResponse?.(address.conversationId, text, ts, replyThreadTs);
123
+ return ts;
124
+ };
118
125
  const state = this.sessions.get(address, sessionKey);
119
126
  if (!state?.running) {
120
127
  await post(formatNothingRunning(bot));
@@ -126,7 +133,9 @@ class ConversationRuntimeImpl {
126
133
  try {
127
134
  const ts = await post(formatStopping(bot));
128
135
  await settlement;
129
- await bot.updateMessage(address.conversationId, ts, formatStopped(bot));
136
+ const stoppedText = formatStopped(bot);
137
+ await bot.updateMessage(address.conversationId, ts, stoppedText);
138
+ bot.logBotResponse?.(address.conversationId, stoppedText, ts, replyThreadTs);
130
139
  }
131
140
  finally {
132
141
  state.stopNoticeOwned = false;
@@ -1 +1 @@
1
- {"version":3,"file":"conversation-runtime.js","sourceRoot":"","sources":["../../src/runtime/conversation-runtime.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAEhG,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAE3F,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AACjC,OAAO,EACL,iBAAiB,EACjB,8BAA8B,EAC9B,aAAa,EACb,kBAAkB,EAClB,WAAW,EACX,qBAAqB,EACrB,WAAW,GACZ,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,eAAe,EACf,0BAA0B,EAC1B,6BAA6B,GAC9B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,oBAAoB,EACpB,yBAAyB,EACzB,2BAA2B,EAC3B,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,qCAAqC,EACrC,gBAAgB,EAChB,cAAc,GACf,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,aAAa,EACb,cAAc,GACf,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,+BAA+B,EAAE,MAAM,qBAAqB,CAAC;AACtE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AA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AC,OAAO,EAAE,eAAe,EAAE,MAAM,CAAC,CACpE,CAAC;IACJ,CAAC;IAEO,KAAK,CAAC,gBAAgB,CAC5B,OAA4D,EAC5D,eAAuB,EACvB,MAAmB;QAEnB,MAAM,CAAC,cAAc,EAAE,CAAC;QACxB,MAAM,EAAE,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,GAAG,OAAO,CAAC;QAC1D,MAAM,UAAU,GAAG,oBAAoB,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC/F,MAAM,YAAY,GAAG,MAAM,IAAI,CAAC,kBAAkB,CAAC,mBAAmB,CAAC;YACrE,eAAe;YACf,UAAU;YACV,GAAG,EAAE,UAAU;YACf,gBAAgB;SACjB,CAAC,CAAC;QACH,MAAM,CAAC,cAAc,EAAE,CAAC;QACxB,OAAO;YACL,OAAO;YACP,UAAU;YACV,OAAO,EAAE,KAAK;YACd,MAAM,EAAE,MAAM,IAAI,CAAC,mBAAmB,CAAC,OAAO,EAAE,YAAY,EAAE,MAAM,CAAC;YACrE,aAAa,EAAE,KAAK;YACpB,cAAc,EAAE,IAAI,CAAC,GAAG,EAAE;YAC1B,WAAW,EAAE,YAAY,CAAC,WAAW;YACrC,SAAS,EAAE,CAAC;SACb,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,QAAQ,CAAC,SAAS,GAAG,MAAM;QAC/B,IAAI,IAAI,CAAC,cAAc;YAAE,OAAO;QAChC,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;QAC3B,GAAG,CAAC,OAAO,CAAC,6BAA6B,CAAC,CAAC;QAC3C,MAAM,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;IAC1C,CAAC;CACF","sourcesContent":["import type {\n MessagingBot,\n ConversationContext,\n ConversationMessage,\n ConversationEvent,\n HandleNewCommandOptions,\n OfficeAddress,\n PlatformName,\n RunningSession,\n} from \"../types.js\";\nimport type { Workspace } from \"../office/index.js\";\nimport { createRunner } from \"../harness/runner.js\";\nimport { commitOfficeDream, generateMemoryAnchor, prepareOfficeDream } from \"../dream/index.js\";\nimport type { PiAgentWrapper } from \"../types.js\";\nimport { MikanModels } from \"../harness/index.js\";\nimport { defaultCommandHandlers, dispatchCommand } from \"../adapters/commands/registry.js\";\nimport type { CommandHandler, CommandServices } from \"../adapters/commands/types.js\";\nimport { isPrivateConversation } from \"../adapters/commands/utils.js\";\nimport * as log from \"../log.js\";\nimport {\n addLifecycleEvent,\n createRunAttributionAttributes,\n recordCounter,\n recordDistribution,\n recordGauge,\n reportUserFacingError,\n withRunSpan,\n} from \"../observability/index.js\";\nimport {\n ChatHistorySync,\n hasMaterializedChatSession,\n waitForThreadSessionBootstrap,\n} from \"../sessions/chat-history-sync.js\";\nimport {\n getThreadSessionFile,\n resolveChannelSessionFile,\n shouldRotateTopLevelSession,\n tryResolveThreadSession,\n} from \"../sessions/store.js\";\nimport {\n assertSessionKeyBelongsToConversation,\n deriveSessionKey,\n threadSuffixOf,\n} from \"../sessions/session-key.js\";\nimport {\n formatNothingRunning,\n formatRestarting,\n formatStopped,\n formatStopping,\n} from \"../adapters/messages.js\";\nimport { getUnresolvedSandboxPathContext } from \"../sandbox/index.js\";\nimport { disabledVaultManager } from \"../vault/index.js\";\nimport type { ConversationRuntimeState } from \"./types.js\";\nimport { SessionLifecycle } from \"./session-lifecycle.js\";\n\ntype ConversationState = ConversationRuntimeState;\n\nexport type {\n RunSessionOptions,\n ConversationRuntime,\n ConversationRuntimeOptions,\n} from \"./types.js\";\nimport type {\n RunSessionOptions,\n ConversationRuntime,\n ConversationRuntimeOptions,\n SessionStateOptions,\n} from \"./types.js\";\n\n/**\n * Placeholder token store for embedders that run without the web portal.\n * Command handlers guard on `portalBaseUrl` before minting tokens, so this\n * only fires when a portal URL is configured without its backing store.\n */\nfunction portalNotConfiguredTokenStore(portal: string): { create: () => never } {\n return {\n create: () => {\n throw new Error(`${portal} portal not configured`);\n },\n };\n}\n\nfunction runtimeCwdForSandbox(\n sandbox: ConversationRuntimeOptions[\"sandbox\"],\n workspace: Workspace,\n address: OfficeAddress,\n): string {\n const runtimeWorkspaceRoot = getUnresolvedSandboxPathContext(\n sandbox,\n workspace.root,\n ).runtimeWorkspaceRoot;\n // The office key names the same segment on the host and in the runtime.\n return `${runtimeWorkspaceRoot.replace(/\\/+$/, \"\")}/${workspace.office(address).key}`;\n}\n\n/** Ask a running session to stop; the run settles through its own abort path. */\nfunction requestStop(state: ConversationRuntimeState): void {\n state.stopRequested = true;\n state.runner.abort();\n}\n\n/** Tell the conversation why its reply stopped: an operator stop, or a shutdown deadline. */\nasync function postAbortNotice(\n state: ConversationRuntimeState,\n bot: MessagingBot,\n conversationId: string,\n platformName: string,\n): Promise<void> {\n if (state.shutdownAborted) {\n recordCounter(\"agent.run.shutdown_aborted\", 1, { platform: platformName });\n await bot.postMessage(conversationId, formatRestarting(bot));\n return;\n }\n if (!state.stopRequested) return;\n if (state.stopNoticeOwned) return;\n const thread = threadSuffixOf(state.sessionKey);\n if (thread && bot.postInThread)\n await bot.postInThread(conversationId, thread, formatStopped(bot));\n else await bot.postMessage(conversationId, formatStopped(bot));\n}\n\nexport function createConversationRuntime(\n options: ConversationRuntimeOptions,\n): ConversationRuntime {\n return new ConversationRuntimeImpl(options);\n}\n\nclass ConversationRuntimeImpl implements ConversationRuntime {\n private readonly sessions = new SessionLifecycle();\n private readonly chatSessionManager = new ChatHistorySync();\n private readonly commandServices: CommandServices;\n private readonly commandHandlers: readonly CommandHandler[];\n private readonly resolvedModels: MikanModels;\n private isShuttingDown = false;\n\n constructor(private readonly options: ConversationRuntimeOptions) {\n this.resolvedModels = options.models ?? MikanModels.create();\n this.commandServices = {\n ...options,\n resourceController: options.resourceController ?? options.provisioner,\n vaultManager: options.vaultManager ?? disabledVaultManager,\n linkTokenStore: options.linkTokenStore ?? portalNotConfiguredTokenStore(\"Login\"),\n sessionViewTokenStore:\n options.sessionViewTokenStore ?? portalNotConfiguredTokenStore(\"Session viewer\"),\n adminTokenStore: options.adminTokenStore ?? portalNotConfiguredTokenStore(\"Admin\"),\n runtime: this,\n };\n this.commandHandlers = options.commandHandlers ?? defaultCommandHandlers(this.resolvedModels);\n }\n\n isRunning(address: OfficeAddress, sessionKey: string): boolean {\n return this.sessions.get(address, sessionKey)?.running === true;\n }\n\n getRunningSessions(): RunningSession[] {\n const sessions: RunningSession[] = [];\n for (const state of this.sessions.runningStates()) {\n if (state.startedAt) {\n const currentStep = state.runner.getCurrentStep();\n sessions.push({\n address: state.address,\n sessionKey: state.sessionKey,\n startedAt: state.startedAt,\n lastActivityAt: state.lastActivityAt,\n currentTool: currentStep?.label || currentStep?.toolName,\n ...(state.stopRequested ? { stopping: true } : {}),\n });\n }\n }\n return sessions;\n }\n\n async runDream(address: OfficeAddress, now = new Date()): Promise<boolean> {\n return this.sessions.runConversationMaintenance(address, async () => {\n const office = this.options.workspace.office(address);\n const plan = await prepareOfficeDream(office, now);\n if (!plan) return false;\n const memory = await generateMemoryAnchor(office, plan, this.resolvedModels);\n commitOfficeDream(office, plan, memory);\n log.logInfo(`[${address.conversationId}] Dream updated the Memory anchor`);\n return true;\n });\n }\n\n async steer(message: ConversationMessage): Promise<boolean> {\n const state = this.sessions.get(message.address, message.sessionKey);\n if (!state?.running) return false;\n return state.runner.steer ? state.runner.steer(message) : false;\n }\n\n async handleStop(\n address: OfficeAddress,\n sessionKey: string,\n bot: MessagingBot,\n replyThreadTs?: string,\n ): Promise<void> {\n assertSessionKeyBelongsToConversation(sessionKey, address.conversationId);\n const post = (text: string) =>\n replyThreadTs && bot.postInThread\n ? bot.postInThread(address.conversationId, replyThreadTs, text)\n : bot.postMessage(address.conversationId, text);\n const state = this.sessions.get(address, sessionKey);\n if (!state?.running) {\n await post(formatNothingRunning(bot));\n return;\n }\n const settlement = state.runSettlement;\n state.stopNoticeOwned = true;\n requestStop(state);\n try {\n const ts = await post(formatStopping(bot));\n await settlement;\n await bot.updateMessage(address.conversationId, ts, formatStopped(bot));\n } finally {\n state.stopNoticeOwned = false;\n }\n }\n\n forceStop(address: OfficeAddress, sessionKey: string): void {\n const state = this.sessions.get(address, sessionKey);\n if (state?.running) {\n log.logInfo(`[Force Stop] Force stopping session: ${sessionKey}`);\n requestStop(state);\n }\n }\n\n async handleNewCommand({\n sessionKey,\n conversationId,\n bot,\n message,\n }: HandleNewCommandOptions): Promise<void> {\n const address = message.address;\n if (conversationId !== address.conversationId) {\n throw new Error(\n `Conversation id ${JSON.stringify(conversationId)} does not match office ` +\n JSON.stringify(address.conversationId),\n );\n }\n assertSessionKeyBelongsToConversation(sessionKey, address.conversationId);\n\n const activeState = this.sessions.get(address, sessionKey);\n if (activeState?.runSettlement) {\n if (activeState.running) requestStop(activeState);\n await activeState.runSettlement;\n }\n\n await this.sessions.runConversationMaintenance(address, async () => {\n await this.resetSession(address, sessionKey, bot);\n });\n }\n\n private scheduleSharedSessionRotation(\n { event, bot, context }: RunSessionOptions,\n sessionKey: string,\n ): boolean {\n const { address, conversationId } = event;\n if (context.message.conversationKind !== \"shared\" || sessionKey !== conversationId)\n return false;\n\n const conversationDir = this.options.workspace.office(address).dir;\n const currentSession = resolveChannelSessionFile(conversationDir);\n if (!currentSession || !shouldRotateTopLevelSession(currentSession, new Date())) return false;\n\n void this.sessions\n .runConversationMaintenance(address, async () => {\n const session = resolveChannelSessionFile(conversationDir);\n if (!session || !shouldRotateTopLevelSession(session, new Date())) {\n await this.runSession({ event, bot, context }, true);\n return;\n }\n\n const runtimeCwd = runtimeCwdForSandbox(\n this.options.sandbox,\n this.options.workspace,\n address,\n );\n await this.chatSessionManager.resetSession({\n conversationDir,\n sessionKey,\n cwd: runtimeCwd,\n });\n await this.sessions.discardAndWait(address, sessionKey);\n log.logInfo(`[${conversationId}] Rotated session: ${sessionKey}`);\n await this.runSession({ event, bot, context }, true);\n })\n .catch((err) => {\n reportUserFacingError(err, {\n domain: \"mikan\",\n surface: \"session_rotation\",\n operation: \"rotate_shared_session_in_background\",\n });\n });\n return true;\n }\n\n private async resetSession(\n address: OfficeAddress,\n sessionKey: string,\n bot: MessagingBot,\n ): Promise<void> {\n const conversationId = address.conversationId;\n const conversationDir = this.options.workspace.office(address).dir;\n const runtimeCwd = runtimeCwdForSandbox(this.options.sandbox, this.options.workspace, address);\n await this.chatSessionManager.resetSession({ conversationDir, sessionKey, cwd: runtimeCwd });\n\n await this.sessions.discardAndWait(address, sessionKey);\n\n log.logInfo(`[${conversationId}] Session reset: ${sessionKey}`);\n await bot.postMessage(conversationId, \"Conversation reset. Send a new message to start fresh.\");\n }\n\n async handleEvent(\n event: ConversationEvent,\n bot: MessagingBot,\n context: ConversationContext,\n ): Promise<void> {\n const sessionKey = deriveSessionKey(event);\n await this.sessions.enqueue(event.address, sessionKey, () =>\n this.runSession({ event, bot, context }),\n );\n }\n\n async runSession(options: RunSessionOptions, skipRotation = false): Promise<void> {\n const { event } = options;\n const conversationId = event.conversationId;\n if (this.isShuttingDown) {\n log.logInfo(\n `[${conversationId}] Rejected event during shutdown: ${event.text.substring(0, 50)}`,\n );\n return;\n }\n\n const sessionKey = deriveSessionKey(event);\n if (await this.handledBeforeRun(options, sessionKey, skipRotation)) return;\n\n const address = event.address;\n const releaseConversationWork = skipRotation\n ? () => {}\n : await this.sessions.acquireConversationWork(address);\n try {\n const conversationDir = this.options.workspace.office(address).dir;\n await this.waitForParentSession(address, sessionKey, conversationDir);\n\n const lease = await this.acquireRunLease(options, sessionKey);\n const { state } = lease;\n log.logInfo(`[${conversationId}] Starting run: ${event.text.substring(0, 50)}`);\n const runPromise = this.sessions.settle(state, () =>\n this.executeRun(options, sessionKey, state),\n );\n lease.release();\n recordGauge(\"agent.sessions.active\", this.sessions.settlementCount());\n await runPromise;\n } finally {\n releaseConversationWork();\n }\n }\n\n /**\n * Guards that can settle an event before any runner work: a session command,\n * an in-flight run for the same session, or a shared-session rotation.\n * Returns true when the event needs no run of its own.\n */\n private async handledBeforeRun(\n options: RunSessionOptions,\n sessionKey: string,\n skipRotation: boolean,\n ): Promise<boolean> {\n const { event } = options;\n if (!skipRotation && (await this.dispatchSessionCommand(options, sessionKey))) return true;\n\n const activeSettlement = this.sessions.get(event.address, sessionKey)?.runSettlement;\n if (activeSettlement) await activeSettlement;\n\n return (\n !skipRotation &&\n sessionKey === event.conversationId &&\n this.scheduleSharedSessionRotation(options, sessionKey)\n );\n }\n\n /** Lease the runner for a run, reporting session-setup failures before rethrowing. */\n private async acquireRunLease(\n { event, context }: RunSessionOptions,\n sessionKey: string,\n ): Promise<{ state: ConversationState; release: () => void }> {\n let lease: { state: ConversationState; release: () => void } | undefined;\n try {\n lease = await this.acquireState({\n address: event.address,\n sessionKey,\n currentMessageId: event.ts,\n trustModel: context.platform.trustModel ?? \"membership\",\n platformWorkspaceId: context.platform.workspaceId,\n });\n await lease.state.runner.syncChatHistory(event.ts);\n return lease;\n } catch (err) {\n lease?.release();\n reportUserFacingError(err, {\n domain: \"mikan\",\n surface: \"session_setup\",\n operation: \"get_or_create_state\",\n severity: \"error\",\n platform: context.platform.name,\n context: {\n conversationId: event.conversationId,\n sessionKey,\n messageId: context.message.id,\n threadTs: context.message.threadTs,\n attachmentCount: context.message.attachments?.length ?? 0,\n },\n });\n throw err;\n }\n }\n\n /** The instrumented agent run, with typing/working indicators and abort notice. */\n private async executeRun(\n { event, bot, context }: RunSessionOptions,\n sessionKey: string,\n state: ConversationState,\n ): Promise<void> {\n const conversationId = event.conversationId;\n try {\n const result = await this.runWithInstrumentation(\n context,\n { conversationId, sessionKey, startedAt: state.startedAt },\n async () => {\n await context.responder.setTyping(true);\n await context.responder.setWorking(true);\n try {\n return await state.runner.run(context.message, context.responder, context.platform);\n } finally {\n await context.responder.setWorking(false);\n }\n },\n );\n\n if (result?.stopReason === \"aborted\") {\n await postAbortNotice(state, bot, conversationId, context.platform.name);\n }\n } finally {\n recordGauge(\"agent.sessions.active\", this.sessions.settlementCount() - 1);\n }\n }\n\n private async waitForParentSession(\n address: OfficeAddress,\n sessionKey: string,\n conversationDir: string,\n ): Promise<void> {\n const conversationId = address.conversationId;\n const waited = await waitForThreadSessionBootstrap({\n parentSessionKey: conversationId,\n sessionKey,\n hasThreadSession: () => hasMaterializedChatSession({ conversationDir, sessionKey }),\n isParentRunning: () => this.sessions.get(address, conversationId)?.running === true,\n });\n if (waited) {\n log.logInfo(\n `[${conversationId}] Delayed thread bootstrap until parent session sealed: ${sessionKey}`,\n );\n }\n }\n\n private async dispatchSessionCommand(\n { event, bot, context }: RunSessionOptions,\n sessionKey: string,\n ): Promise<boolean> {\n return dispatchCommand(this.commandHandlers, {\n bot,\n responder: context.responder,\n platform: context.platform.name as PlatformName,\n address: event.address,\n platformUserId: event.user,\n platformUserName: context.message.userName,\n conversationId: event.conversationId,\n vaultConversationId: event.vaultConversationId,\n sessionKey,\n commandText: event.text,\n privateConversation: isPrivateConversation(event),\n services: this.commandServices,\n });\n }\n\n private async runWithInstrumentation(\n context: ConversationContext,\n meta: {\n conversationId: string;\n sessionKey: string;\n startedAt: number;\n },\n body: () => Promise<{ stopReason: string; errorMessage?: string }>,\n ): Promise<{ stopReason: string; errorMessage?: string } | undefined> {\n const { conversationId, sessionKey, startedAt } = meta;\n const { message, platform } = context;\n\n const attribution = createRunAttributionAttributes({\n conversationId,\n sessionKey,\n messageId: message.id,\n platform: platform.name,\n conversationKind: message.conversationKind,\n userId: message.userId,\n userName: message.userName,\n threadTs: message.threadTs,\n });\n\n recordCounter(\"agent.run.started\", 1, attribution);\n\n return withRunSpan(\n {\n conversationId,\n sessionKey,\n messageId: message.id,\n platform: platform.name,\n conversationKind: message.conversationKind,\n userId: message.userId,\n userName: message.userName,\n threadTs: message.threadTs,\n },\n async () => {\n addLifecycleEvent(\"agent.run.started\", {\n channel_id: attribution.channel_id,\n platform: platform.name,\n conversation_kind: message.conversationKind,\n has_attachments: (message.attachments?.length ?? 0) > 0,\n });\n\n try {\n const result = await body();\n const durationMs = Date.now() - startedAt;\n const completionAttrs = {\n ...attribution,\n stop_reason: result.stopReason,\n };\n recordDistribution(\"agent.run.duration\", durationMs, {\n unit: \"millisecond\",\n attributes: completionAttrs,\n });\n recordCounter(\"agent.run.completed\", 1, completionAttrs);\n addLifecycleEvent(\"agent.run.completed\", {\n channel_id: attribution.channel_id,\n platform: platform.name,\n stop_reason: result.stopReason,\n duration_ms: durationMs,\n });\n return result;\n } catch (err) {\n reportUserFacingError(err, {\n domain: \"mikan\",\n surface: \"agent_run\",\n operation: \"run\",\n severity: \"error\",\n platform: platform.name,\n context: {\n conversationId,\n sessionKey,\n messageId: message.id,\n threadTs: message.threadTs,\n attachmentCount: message.attachments?.length ?? 0,\n },\n });\n recordCounter(\"agent.run.errors\", 1, attribution);\n log.logWarning(\n `[${conversationId}] Run error`,\n err instanceof Error ? err.message : String(err),\n );\n await context.responder\n .replaceResponse(\"Could not complete the request. Please reply to retry or revise it.\")\n .catch(() => {});\n return undefined;\n }\n },\n );\n }\n\n switchConversationModel(address: OfficeAddress, _provider: string, _model: string): boolean {\n return this.invalidateOffice(address, \"Model switched\");\n }\n\n refreshConversationEnvironment(address: OfficeAddress): boolean {\n return this.invalidateOffice(address, \"Environment refreshed\");\n }\n\n refreshAllConversations(): { busy: OfficeAddress[] } {\n const offices = this.sessions.offices();\n const result = this.sessions.invalidateAll();\n const busyKeys = new Set(\n result.busy.map((address) => `${address.platform}:${address.conversationId}`),\n );\n for (const address of offices) {\n if (busyKeys.has(`${address.platform}:${address.conversationId}`)) continue;\n log.logInfo(\n `[${address.conversationId}] Global settings changed; cleared cached session runners`,\n );\n }\n return result;\n }\n\n private invalidateOffice(address: OfficeAddress, reason: string): boolean {\n const cleared = this.sessions.invalidateConversation(address);\n if (cleared) {\n log.logInfo(`[${address.conversationId}] ${reason}; cleared cached session runners`);\n }\n return cleared;\n }\n\n private async createCurrentRunner(\n options: SessionStateOptions,\n sessionScope: Awaited<ReturnType<ChatHistorySync[\"resolveSessionScope\"]>>,\n signal: AbortSignal,\n ): Promise<PiAgentWrapper> {\n return createRunner({\n sandboxConfig: this.options.sandbox,\n sessionKey: options.sessionKey,\n office: this.options.workspace.office(options.address),\n trustModel: options.trustModel,\n platformWorkspaceId: options.platformWorkspaceId,\n openConnector: this.options.openConnector,\n eventScheduler: this.options.eventScheduler?.(),\n sessionScope,\n signal,\n vaultManager: this.options.vaultManager,\n provisioner: this.options.provisioner,\n resourceController: this.options.resourceController,\n sessionView: this.options.sessionViewTokenStore\n ? {\n tokenStore: this.options.sessionViewTokenStore,\n portalBaseUrl: this.options.portalBaseUrl,\n }\n : undefined,\n platformToolPackFactories: this.options.platformToolPackFactories,\n models: this.resolvedModels,\n });\n }\n\n private acquireState(options: SessionStateOptions & { currentMessageId?: string }) {\n const { address, sessionKey } = options;\n const conversationDir = this.options.workspace.office(address).dir;\n return this.sessions.acquire(\n address,\n sessionKey,\n () =>\n sessionKey === address.conversationId\n ? resolveChannelSessionFile(conversationDir)\n : tryResolveThreadSession(getThreadSessionFile(conversationDir, sessionKey)),\n (signal) => this.materializeState(options, conversationDir, signal),\n );\n }\n\n private async materializeState(\n options: SessionStateOptions & { currentMessageId?: string },\n conversationDir: string,\n signal: AbortSignal,\n ): Promise<ConversationState> {\n signal.throwIfAborted();\n const { address, sessionKey, currentMessageId } = options;\n const runtimeCwd = runtimeCwdForSandbox(this.options.sandbox, this.options.workspace, address);\n const sessionScope = await this.chatSessionManager.resolveSessionScope({\n conversationDir,\n sessionKey,\n cwd: runtimeCwd,\n currentMessageId,\n });\n signal.throwIfAborted();\n return {\n address,\n sessionKey,\n running: false,\n runner: await this.createCurrentRunner(options, sessionScope, signal),\n stopRequested: false,\n lastAccessedAt: Date.now(),\n sessionFile: sessionScope.contextFile,\n startedAt: 0,\n };\n }\n\n async shutdown(timeoutMs = 30_000): Promise<void> {\n if (this.isShuttingDown) return;\n this.isShuttingDown = true;\n log.logInfo(\"Shutting down gracefully...\");\n await this.sessions.shutdown(timeoutMs);\n }\n}\n"]}
1
+ {"version":3,"file":"conversation-runtime.js","sourceRoot":"","sources":["../../src/runtime/conversation-runtime.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAEhG,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAE3F,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AACjC,OAAO,EACL,iBAAiB,EACjB,8BAA8B,EAC9B,aAAa,EACb,kBAAkB,EAClB,WAAW,EACX,qBAAqB,EACrB,WAAW,GACZ,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,eAAe,EACf,0BAA0B,EAC1B,6BAA6B,GAC9B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,oBAAoB,EACpB,yBAAyB,EACzB,2BAA2B,EAC3B,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,qCAAqC,EACrC,gBAAgB,EAChB,cAAc,GACf,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,aAAa,EACb,cAAc,GACf,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,+BAA+B,EAAE,MAAM,qBAAqB,CAAC;AACtE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAEzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAgB1D;;;;GAIG;AACH,SAAS,6BAA6B,CAAC,MAAc;IACnD,OAAO;QACL,MAAM,EAAE,GAAG,EAAE;YACX,MAAM,IAAI,KAAK,CAAC,GAAG,MAAM,wBAAwB,CAAC,CAAC;QACrD,CAAC;KACF,CAAC;AACJ,CA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AAQ,CAAC,SAAS,GAAG,MAAM;QAC/B,IAAI,IAAI,CAAC,cAAc;YAAE,OAAO;QAChC,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;QAC3B,GAAG,CAAC,OAAO,CAAC,6BAA6B,CAAC,CAAC;QAC3C,MAAM,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;IAC1C,CAAC;CACF","sourcesContent":["import type {\n MessagingBot,\n ConversationContext,\n ConversationMessage,\n ConversationEvent,\n HandleNewCommandOptions,\n OfficeAddress,\n PlatformName,\n RunningSession,\n} from \"../types.js\";\nimport type { Workspace } from \"../office/index.js\";\nimport { createRunner } from \"../harness/runner.js\";\nimport { commitOfficeDream, generateMemoryAnchor, prepareOfficeDream } from \"../dream/index.js\";\nimport type { PiAgentWrapper } from \"../types.js\";\nimport { MikanModels } from \"../harness/index.js\";\nimport { defaultCommandHandlers, dispatchCommand } from \"../adapters/commands/registry.js\";\nimport type { CommandHandler, CommandServices } from \"../adapters/commands/types.js\";\nimport { isPrivateConversation } from \"../adapters/commands/utils.js\";\nimport * as log from \"../log.js\";\nimport {\n addLifecycleEvent,\n createRunAttributionAttributes,\n recordCounter,\n recordDistribution,\n recordGauge,\n reportUserFacingError,\n withRunSpan,\n} from \"../observability/index.js\";\nimport {\n ChatHistorySync,\n hasMaterializedChatSession,\n waitForThreadSessionBootstrap,\n} from \"../sessions/chat-history-sync.js\";\nimport {\n getThreadSessionFile,\n resolveChannelSessionFile,\n shouldRotateTopLevelSession,\n tryResolveThreadSession,\n} from \"../sessions/store.js\";\nimport {\n assertSessionKeyBelongsToConversation,\n deriveSessionKey,\n threadSuffixOf,\n} from \"../sessions/session-key.js\";\nimport {\n formatNothingRunning,\n formatRestarting,\n formatStopped,\n formatStopping,\n} from \"../adapters/messages.js\";\nimport { getUnresolvedSandboxPathContext } from \"../sandbox/index.js\";\nimport { disabledVaultManager } from \"../vault/index.js\";\nimport type { ConversationRuntimeState } from \"./types.js\";\nimport { SessionLifecycle } from \"./session-lifecycle.js\";\n\ntype ConversationState = ConversationRuntimeState;\n\nexport type {\n RunSessionOptions,\n ConversationRuntime,\n ConversationRuntimeOptions,\n} from \"./types.js\";\nimport type {\n RunSessionOptions,\n ConversationRuntime,\n ConversationRuntimeOptions,\n SessionStateOptions,\n} from \"./types.js\";\n\n/**\n * Placeholder token store for embedders that run without the web portal.\n * Command handlers guard on `portalBaseUrl` before minting tokens, so this\n * only fires when a portal URL is configured without its backing store.\n */\nfunction portalNotConfiguredTokenStore(portal: string): { create: () => never } {\n return {\n create: () => {\n throw new Error(`${portal} portal not configured`);\n },\n };\n}\n\nfunction runtimeCwdForSandbox(\n sandbox: ConversationRuntimeOptions[\"sandbox\"],\n workspace: Workspace,\n address: OfficeAddress,\n): string {\n const runtimeWorkspaceRoot = getUnresolvedSandboxPathContext(\n sandbox,\n workspace.root,\n ).runtimeWorkspaceRoot;\n // The office key names the same segment on the host and in the runtime.\n return `${runtimeWorkspaceRoot.replace(/\\/+$/, \"\")}/${workspace.office(address).key}`;\n}\n\n/** Ask a running session to stop; the run settles through its own abort path. */\nfunction requestStop(state: ConversationRuntimeState): void {\n state.stopRequested = true;\n state.runner.abort();\n}\n\n/** Tell the conversation why its reply stopped: an operator stop, or a shutdown deadline. */\nasync function postAbortNotice(\n state: ConversationRuntimeState,\n bot: MessagingBot,\n conversationId: string,\n platformName: string,\n): Promise<void> {\n if (state.shutdownAborted) {\n recordCounter(\"agent.run.shutdown_aborted\", 1, { platform: platformName });\n const text = formatRestarting(bot);\n const ts = await bot.postMessage(conversationId, text);\n bot.logBotResponse?.(conversationId, text, ts);\n return;\n }\n if (!state.stopRequested) return;\n if (state.stopNoticeOwned) return;\n const thread = threadSuffixOf(state.sessionKey) ?? undefined;\n const text = formatStopped(bot);\n const ts =\n thread && bot.postInThread\n ? await bot.postInThread(conversationId, thread, text)\n : await bot.postMessage(conversationId, text);\n bot.logBotResponse?.(conversationId, text, ts, thread);\n}\n\nexport function createConversationRuntime(\n options: ConversationRuntimeOptions,\n): ConversationRuntime {\n return new ConversationRuntimeImpl(options);\n}\n\nclass ConversationRuntimeImpl implements ConversationRuntime {\n private readonly sessions = new SessionLifecycle();\n private readonly chatSessionManager = new ChatHistorySync();\n private readonly commandServices: CommandServices;\n private readonly commandHandlers: readonly CommandHandler[];\n private readonly resolvedModels: MikanModels;\n private isShuttingDown = false;\n\n constructor(private readonly options: ConversationRuntimeOptions) {\n this.resolvedModels = options.models ?? MikanModels.create();\n this.commandServices = {\n ...options,\n resourceController: options.resourceController ?? options.provisioner,\n vaultManager: options.vaultManager ?? disabledVaultManager,\n linkTokenStore: options.linkTokenStore ?? portalNotConfiguredTokenStore(\"Login\"),\n sessionViewTokenStore:\n options.sessionViewTokenStore ?? portalNotConfiguredTokenStore(\"Session viewer\"),\n adminTokenStore: options.adminTokenStore ?? portalNotConfiguredTokenStore(\"Admin\"),\n runtime: this,\n };\n this.commandHandlers = options.commandHandlers ?? defaultCommandHandlers(this.resolvedModels);\n }\n\n isRunning(address: OfficeAddress, sessionKey: string): boolean {\n return this.sessions.get(address, sessionKey)?.running === true;\n }\n\n getRunningSessions(): RunningSession[] {\n const sessions: RunningSession[] = [];\n for (const state of this.sessions.runningStates()) {\n if (state.startedAt) {\n const currentStep = state.runner.getCurrentStep();\n sessions.push({\n address: state.address,\n sessionKey: state.sessionKey,\n startedAt: state.startedAt,\n lastActivityAt: state.lastActivityAt,\n currentTool: currentStep?.label || currentStep?.toolName,\n ...(state.stopRequested ? { stopping: true } : {}),\n });\n }\n }\n return sessions;\n }\n\n async runDream(address: OfficeAddress, now = new Date()): Promise<boolean> {\n return this.sessions.runConversationMaintenance(address, async () => {\n const office = this.options.workspace.office(address);\n const plan = await prepareOfficeDream(office, now);\n if (!plan) return false;\n const memory = await generateMemoryAnchor(office, plan, this.resolvedModels);\n commitOfficeDream(office, plan, memory);\n log.logInfo(`[${address.conversationId}] Dream updated the Memory anchor`);\n return true;\n });\n }\n\n async steer(message: ConversationMessage): Promise<boolean> {\n const state = this.sessions.get(message.address, message.sessionKey);\n if (!state?.running) return false;\n return state.runner.steer ? state.runner.steer(message) : false;\n }\n\n async handleStop(\n address: OfficeAddress,\n sessionKey: string,\n bot: MessagingBot,\n replyThreadTs?: string,\n ): Promise<void> {\n assertSessionKeyBelongsToConversation(sessionKey, address.conversationId);\n const post = async (text: string) => {\n const ts =\n replyThreadTs && bot.postInThread\n ? await bot.postInThread(address.conversationId, replyThreadTs, text)\n : await bot.postMessage(address.conversationId, text);\n bot.logBotResponse?.(address.conversationId, text, ts, replyThreadTs);\n return ts;\n };\n const state = this.sessions.get(address, sessionKey);\n if (!state?.running) {\n await post(formatNothingRunning(bot));\n return;\n }\n const settlement = state.runSettlement;\n state.stopNoticeOwned = true;\n requestStop(state);\n try {\n const ts = await post(formatStopping(bot));\n await settlement;\n const stoppedText = formatStopped(bot);\n await bot.updateMessage(address.conversationId, ts, stoppedText);\n bot.logBotResponse?.(address.conversationId, stoppedText, ts, replyThreadTs);\n } finally {\n state.stopNoticeOwned = false;\n }\n }\n\n forceStop(address: OfficeAddress, sessionKey: string): void {\n const state = this.sessions.get(address, sessionKey);\n if (state?.running) {\n log.logInfo(`[Force Stop] Force stopping session: ${sessionKey}`);\n requestStop(state);\n }\n }\n\n async handleNewCommand({\n sessionKey,\n conversationId,\n bot,\n message,\n }: HandleNewCommandOptions): Promise<void> {\n const address = message.address;\n if (conversationId !== address.conversationId) {\n throw new Error(\n `Conversation id ${JSON.stringify(conversationId)} does not match office ` +\n JSON.stringify(address.conversationId),\n );\n }\n assertSessionKeyBelongsToConversation(sessionKey, address.conversationId);\n\n const activeState = this.sessions.get(address, sessionKey);\n if (activeState?.runSettlement) {\n if (activeState.running) requestStop(activeState);\n await activeState.runSettlement;\n }\n\n await this.sessions.runConversationMaintenance(address, async () => {\n await this.resetSession(address, sessionKey, bot);\n });\n }\n\n private scheduleSharedSessionRotation(\n { event, bot, context }: RunSessionOptions,\n sessionKey: string,\n ): boolean {\n const { address, conversationId } = event;\n if (context.message.conversationKind !== \"shared\" || sessionKey !== conversationId)\n return false;\n\n const conversationDir = this.options.workspace.office(address).dir;\n const currentSession = resolveChannelSessionFile(conversationDir);\n if (!currentSession || !shouldRotateTopLevelSession(currentSession, new Date())) return false;\n\n void this.sessions\n .runConversationMaintenance(address, async () => {\n const session = resolveChannelSessionFile(conversationDir);\n if (!session || !shouldRotateTopLevelSession(session, new Date())) {\n await this.runSession({ event, bot, context }, true);\n return;\n }\n\n const runtimeCwd = runtimeCwdForSandbox(\n this.options.sandbox,\n this.options.workspace,\n address,\n );\n await this.chatSessionManager.resetSession({\n conversationDir,\n sessionKey,\n cwd: runtimeCwd,\n });\n await this.sessions.discardAndWait(address, sessionKey);\n log.logInfo(`[${conversationId}] Rotated session: ${sessionKey}`);\n await this.runSession({ event, bot, context }, true);\n })\n .catch((err) => {\n reportUserFacingError(err, {\n domain: \"mikan\",\n surface: \"session_rotation\",\n operation: \"rotate_shared_session_in_background\",\n });\n });\n return true;\n }\n\n private async resetSession(\n address: OfficeAddress,\n sessionKey: string,\n bot: MessagingBot,\n ): Promise<void> {\n const conversationId = address.conversationId;\n const conversationDir = this.options.workspace.office(address).dir;\n const runtimeCwd = runtimeCwdForSandbox(this.options.sandbox, this.options.workspace, address);\n await this.chatSessionManager.resetSession({ conversationDir, sessionKey, cwd: runtimeCwd });\n\n await this.sessions.discardAndWait(address, sessionKey);\n\n log.logInfo(`[${conversationId}] Session reset: ${sessionKey}`);\n await bot.postMessage(conversationId, \"Conversation reset. Send a new message to start fresh.\");\n }\n\n async handleEvent(\n event: ConversationEvent,\n bot: MessagingBot,\n context: ConversationContext,\n ): Promise<void> {\n const sessionKey = deriveSessionKey(event);\n await this.sessions.enqueue(event.address, sessionKey, () =>\n this.runSession({ event, bot, context }),\n );\n }\n\n async runSession(options: RunSessionOptions, skipRotation = false): Promise<void> {\n const { event } = options;\n const conversationId = event.conversationId;\n if (this.isShuttingDown) {\n log.logInfo(\n `[${conversationId}] Rejected event during shutdown: ${event.text.substring(0, 50)}`,\n );\n return;\n }\n\n const sessionKey = deriveSessionKey(event);\n if (await this.handledBeforeRun(options, sessionKey, skipRotation)) return;\n\n const address = event.address;\n const releaseConversationWork = skipRotation\n ? () => {}\n : await this.sessions.acquireConversationWork(address);\n try {\n const conversationDir = this.options.workspace.office(address).dir;\n await this.waitForParentSession(address, sessionKey, conversationDir);\n\n const lease = await this.acquireRunLease(options, sessionKey);\n const { state } = lease;\n log.logInfo(`[${conversationId}] Starting run: ${event.text.substring(0, 50)}`);\n const runPromise = this.sessions.settle(state, () =>\n this.executeRun(options, sessionKey, state),\n );\n lease.release();\n recordGauge(\"agent.sessions.active\", this.sessions.settlementCount());\n await runPromise;\n } finally {\n releaseConversationWork();\n }\n }\n\n /**\n * Guards that can settle an event before any runner work: a session command,\n * an in-flight run for the same session, or a shared-session rotation.\n * Returns true when the event needs no run of its own.\n */\n private async handledBeforeRun(\n options: RunSessionOptions,\n sessionKey: string,\n skipRotation: boolean,\n ): Promise<boolean> {\n const { event } = options;\n if (!skipRotation && (await this.dispatchSessionCommand(options, sessionKey))) return true;\n\n const activeSettlement = this.sessions.get(event.address, sessionKey)?.runSettlement;\n if (activeSettlement) await activeSettlement;\n\n return (\n !skipRotation &&\n sessionKey === event.conversationId &&\n this.scheduleSharedSessionRotation(options, sessionKey)\n );\n }\n\n /** Lease the runner for a run, reporting session-setup failures before rethrowing. */\n private async acquireRunLease(\n { event, context }: RunSessionOptions,\n sessionKey: string,\n ): Promise<{ state: ConversationState; release: () => void }> {\n let lease: { state: ConversationState; release: () => void } | undefined;\n try {\n lease = await this.acquireState({\n address: event.address,\n sessionKey,\n currentMessageId: event.ts,\n trustModel: context.platform.trustModel ?? \"membership\",\n platformWorkspaceId: context.platform.workspaceId,\n });\n await lease.state.runner.syncChatHistory(event.ts);\n return lease;\n } catch (err) {\n lease?.release();\n reportUserFacingError(err, {\n domain: \"mikan\",\n surface: \"session_setup\",\n operation: \"get_or_create_state\",\n severity: \"error\",\n platform: context.platform.name,\n context: {\n conversationId: event.conversationId,\n sessionKey,\n messageId: context.message.id,\n threadTs: context.message.threadTs,\n attachmentCount: context.message.attachments?.length ?? 0,\n },\n });\n throw err;\n }\n }\n\n /** The instrumented agent run, with typing/working indicators and abort notice. */\n private async executeRun(\n { event, bot, context }: RunSessionOptions,\n sessionKey: string,\n state: ConversationState,\n ): Promise<void> {\n const conversationId = event.conversationId;\n try {\n const result = await this.runWithInstrumentation(\n context,\n { conversationId, sessionKey, startedAt: state.startedAt },\n async () => {\n await context.responder.setTyping(true);\n await context.responder.setWorking(true);\n try {\n return await state.runner.run(context.message, context.responder, context.platform);\n } finally {\n await context.responder.setWorking(false);\n }\n },\n );\n\n if (result?.stopReason === \"aborted\") {\n await postAbortNotice(state, bot, conversationId, context.platform.name);\n }\n } finally {\n recordGauge(\"agent.sessions.active\", this.sessions.settlementCount() - 1);\n }\n }\n\n private async waitForParentSession(\n address: OfficeAddress,\n sessionKey: string,\n conversationDir: string,\n ): Promise<void> {\n const conversationId = address.conversationId;\n const waited = await waitForThreadSessionBootstrap({\n parentSessionKey: conversationId,\n sessionKey,\n hasThreadSession: () => hasMaterializedChatSession({ conversationDir, sessionKey }),\n isParentRunning: () => this.sessions.get(address, conversationId)?.running === true,\n });\n if (waited) {\n log.logInfo(\n `[${conversationId}] Delayed thread bootstrap until parent session sealed: ${sessionKey}`,\n );\n }\n }\n\n private async dispatchSessionCommand(\n { event, bot, context }: RunSessionOptions,\n sessionKey: string,\n ): Promise<boolean> {\n return dispatchCommand(this.commandHandlers, {\n bot,\n responder: context.responder,\n platform: context.platform.name as PlatformName,\n address: event.address,\n platformUserId: event.user,\n platformUserName: context.message.userName,\n conversationId: event.conversationId,\n vaultConversationId: event.vaultConversationId,\n sessionKey,\n commandText: event.text,\n privateConversation: isPrivateConversation(event),\n services: this.commandServices,\n });\n }\n\n private async runWithInstrumentation(\n context: ConversationContext,\n meta: {\n conversationId: string;\n sessionKey: string;\n startedAt: number;\n },\n body: () => Promise<{ stopReason: string; errorMessage?: string }>,\n ): Promise<{ stopReason: string; errorMessage?: string } | undefined> {\n const { conversationId, sessionKey, startedAt } = meta;\n const { message, platform } = context;\n\n const attribution = createRunAttributionAttributes({\n conversationId,\n sessionKey,\n messageId: message.id,\n platform: platform.name,\n conversationKind: message.conversationKind,\n userId: message.userId,\n userName: message.userName,\n threadTs: message.threadTs,\n });\n\n recordCounter(\"agent.run.started\", 1, attribution);\n\n return withRunSpan(\n {\n conversationId,\n sessionKey,\n messageId: message.id,\n platform: platform.name,\n conversationKind: message.conversationKind,\n userId: message.userId,\n userName: message.userName,\n threadTs: message.threadTs,\n },\n async () => {\n addLifecycleEvent(\"agent.run.started\", {\n channel_id: attribution.channel_id,\n platform: platform.name,\n conversation_kind: message.conversationKind,\n has_attachments: (message.attachments?.length ?? 0) > 0,\n });\n\n try {\n const result = await body();\n const durationMs = Date.now() - startedAt;\n const completionAttrs = {\n ...attribution,\n stop_reason: result.stopReason,\n };\n recordDistribution(\"agent.run.duration\", durationMs, {\n unit: \"millisecond\",\n attributes: completionAttrs,\n });\n recordCounter(\"agent.run.completed\", 1, completionAttrs);\n addLifecycleEvent(\"agent.run.completed\", {\n channel_id: attribution.channel_id,\n platform: platform.name,\n stop_reason: result.stopReason,\n duration_ms: durationMs,\n });\n return result;\n } catch (err) {\n reportUserFacingError(err, {\n domain: \"mikan\",\n surface: \"agent_run\",\n operation: \"run\",\n severity: \"error\",\n platform: platform.name,\n context: {\n conversationId,\n sessionKey,\n messageId: message.id,\n threadTs: message.threadTs,\n attachmentCount: message.attachments?.length ?? 0,\n },\n });\n recordCounter(\"agent.run.errors\", 1, attribution);\n log.logWarning(\n `[${conversationId}] Run error`,\n err instanceof Error ? err.message : String(err),\n );\n await context.responder\n .replaceResponse(\"Could not complete the request. Please reply to retry or revise it.\")\n .catch(() => {});\n return undefined;\n }\n },\n );\n }\n\n switchConversationModel(address: OfficeAddress, _provider: string, _model: string): boolean {\n return this.invalidateOffice(address, \"Model switched\");\n }\n\n refreshConversationEnvironment(address: OfficeAddress): boolean {\n return this.invalidateOffice(address, \"Environment refreshed\");\n }\n\n refreshAllConversations(): { busy: OfficeAddress[] } {\n const offices = this.sessions.offices();\n const result = this.sessions.invalidateAll();\n const busyKeys = new Set(\n result.busy.map((address) => `${address.platform}:${address.conversationId}`),\n );\n for (const address of offices) {\n if (busyKeys.has(`${address.platform}:${address.conversationId}`)) continue;\n log.logInfo(\n `[${address.conversationId}] Global settings changed; cleared cached session runners`,\n );\n }\n return result;\n }\n\n private invalidateOffice(address: OfficeAddress, reason: string): boolean {\n const cleared = this.sessions.invalidateConversation(address);\n if (cleared) {\n log.logInfo(`[${address.conversationId}] ${reason}; cleared cached session runners`);\n }\n return cleared;\n }\n\n private async createCurrentRunner(\n options: SessionStateOptions,\n sessionScope: Awaited<ReturnType<ChatHistorySync[\"resolveSessionScope\"]>>,\n signal: AbortSignal,\n ): Promise<PiAgentWrapper> {\n return createRunner({\n sandboxConfig: this.options.sandbox,\n sessionKey: options.sessionKey,\n office: this.options.workspace.office(options.address),\n trustModel: options.trustModel,\n platformWorkspaceId: options.platformWorkspaceId,\n openConnector: this.options.openConnector,\n eventScheduler: this.options.eventScheduler?.(),\n sessionScope,\n signal,\n vaultManager: this.options.vaultManager,\n provisioner: this.options.provisioner,\n resourceController: this.options.resourceController,\n sessionView: this.options.sessionViewTokenStore\n ? {\n tokenStore: this.options.sessionViewTokenStore,\n portalBaseUrl: this.options.portalBaseUrl,\n }\n : undefined,\n platformToolPackFactories: this.options.platformToolPackFactories,\n models: this.resolvedModels,\n });\n }\n\n private acquireState(options: SessionStateOptions & { currentMessageId?: string }) {\n const { address, sessionKey } = options;\n const conversationDir = this.options.workspace.office(address).dir;\n return this.sessions.acquire(\n address,\n sessionKey,\n () =>\n sessionKey === address.conversationId\n ? resolveChannelSessionFile(conversationDir)\n : tryResolveThreadSession(getThreadSessionFile(conversationDir, sessionKey)),\n (signal) => this.materializeState(options, conversationDir, signal),\n );\n }\n\n private async materializeState(\n options: SessionStateOptions & { currentMessageId?: string },\n conversationDir: string,\n signal: AbortSignal,\n ): Promise<ConversationState> {\n signal.throwIfAborted();\n const { address, sessionKey, currentMessageId } = options;\n const runtimeCwd = runtimeCwdForSandbox(this.options.sandbox, this.options.workspace, address);\n const sessionScope = await this.chatSessionManager.resolveSessionScope({\n conversationDir,\n sessionKey,\n cwd: runtimeCwd,\n currentMessageId,\n });\n signal.throwIfAborted();\n return {\n address,\n sessionKey,\n running: false,\n runner: await this.createCurrentRunner(options, sessionScope, signal),\n stopRequested: false,\n lastAccessedAt: Date.now(),\n sessionFile: sessionScope.contextFile,\n startedAt: 0,\n };\n }\n\n async shutdown(timeoutMs = 30_000): Promise<void> {\n if (this.isShuttingDown) return;\n this.isShuttingDown = true;\n log.logInfo(\"Shutting down gracefully...\");\n await this.sessions.shutdown(timeoutMs);\n }\n}\n"]}
package/dist/types.d.ts CHANGED
@@ -268,6 +268,14 @@ export interface MessagingBot {
268
268
  fetchHistory?(channel: string, options?: PlatformHistoryOptions): Promise<PlatformHistoryMessage[]>;
269
269
  /** List the platform workspace's active users. Optional capability. */
270
270
  listUsers?(): Promise<PlatformUserInfo[]>;
271
+ /**
272
+ * Record the bot's own outbound message in the conversation's human-readable
273
+ * `log.jsonl`, mirroring the entry `logToFile` would write for an agent
274
+ * reply. Optional so adapters adopt it incrementally; callers that skip it
275
+ * leave that message invisible to `log.jsonl` history (and to the agent's
276
+ * own greps over it) even though the platform delivered it.
277
+ */
278
+ logBotResponse?(channel: string, text: string, ts: string, threadTs?: string): void;
271
279
  enqueueEvent(event: ConversationEvent): boolean;
272
280
  getMessagingInfo(): MessagingInfo;
273
281
  postPrivate?(conversationId: string, userId: string, text: string): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,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;IACvF,aAAa,CAAC,EAAE,eAAe,CAAC;IAChC,iFAAiF;IACjF,cAAc,CAAC,EAAE,iBAAiB,CAAC;IACnC,YAAY,EAAE,oBAAoB,CAAC;IACnC,yGAAyG;IACzG,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,WAAW,CAAC,EAAE,sBAAsB,CAAC;IACrC,kBAAkB,CAAC,EAAE,yBAAyB,CAAC;IAC/C,WAAW,CAAC,EAAE;QACZ,UAAU,EAAE,yBAAyB,CAAC;QACtC,aAAa,CAAC,EAAE,MAAM,CAAC;KACxB,CAAC;IACF,yBAAyB,CAAC,EAAE,SAAS,uBAAuB,EAAE,CAAC;IAC/D,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAatC,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { SubagentRunStatus } from \"./harness/types.js\";\nimport type { SessionViewTokenStoreLike } from \"./adapters/commands/types.js\";\nimport type { MikanModels } from \"./harness/models.js\";\nimport type { McpServerConfig } from \"./harness/types.js\";\nimport type { EventScheduleSink } from \"./events/index.js\";\nimport type { Office } from \"./office/types.js\";\nimport type { DockerContainerManager } from \"./sandbox/provisioner.js\";\nimport type { SandboxConfig } from \"./sandbox/types.js\";\nimport type { ResolvedSessionScope } from \"./sessions/types.js\";\nimport type { PlatformToolPackFactory } from \"./harness/tools/types.js\";\nimport type { VaultManager } from \"./vault/types.js\";\n\nconst execFileAsync = promisify(execFile);\ntype ExecFileAsync = typeof execFileAsync;\n\n// ── adapter ───────────────────────────────────────────────────────────────────\n\nexport type ConversationKind = \"direct\" | \"shared\";\n\nexport type PlatformName = \"slack\" | \"discord\" | \"telegram\" | \"github\";\n\n/** Canonical platform-plus-raw identifier for one conversation office. */\nexport interface OfficeAddress {\n readonly platform: PlatformName;\n readonly conversationId: string;\n}\n\n/** Stable, filesystem-safe identity derived from an OfficeAddress. */\nexport type OfficeKey = string & { readonly __brand: \"OfficeKey\" };\n\nexport type OfficeMigrationStatus = \"needs-owner\" | \"prepared\" | \"moving\" | \"committed\" | \"failed\";\n\nexport interface OfficeMigrationRecord {\n readonly rawConversationId: string;\n readonly sourceDir: string;\n readonly workspaceRoot: string;\n readonly ownerPlatform?: PlatformName;\n readonly targetDir?: string;\n readonly status: OfficeMigrationStatus;\n readonly error?: string;\n readonly updatedAt: string;\n}\n\n/**\n * Directory entry for one conversation office. The workspace dir name stops\n * carrying the raw platform id once the ADR 0005 layout migration lands, so\n * the registry is the durable raw-id ↔ office mapping used for enumeration.\n */\nexport interface OfficeRecord {\n readonly platform: PlatformName;\n readonly conversationId: string;\n readonly recordedAt: string;\n}\n\nexport interface OfficeRegistryState {\n readonly version: 1;\n readonly enabledPlatforms: readonly PlatformName[];\n readonly offices: readonly OfficeRecord[];\n readonly migrations: readonly OfficeMigrationRecord[];\n}\n\nexport interface OfficeMigrationPreparation {\n readonly rawConversationId: string;\n readonly sourceDir: string;\n readonly workspaceRoot: string;\n readonly ownerPlatform?: PlatformName;\n}\n\n/**\n * Who can drive conversations on a platform — gates ambient credential policy.\n *\n * - `membership`: only invited workspace/server members (Slack/Discord/Telegram).\n * Safe to copy `sandbox.defaultSharedVault` into new conversation vaults.\n * - `open-trigger`: broader trigger surface (e.g. GitHub repo writers on public\n * issues/PRs). Ambient shared vault must not apply; use host-side platform\n * identity or an explicitly provisioned vault.\n */\nexport type PlatformTrustModel = \"membership\" | \"open-trigger\";\n\nexport interface ConversationMessage {\n id: string;\n /** Canonical identity of the conversation office. */\n address: OfficeAddress;\n /** @deprecated Use address.conversationId except at platform I/O seams. */\n conversationId?: string;\n sessionKey: string;\n conversationKind: ConversationKind;\n userId: string;\n userName?: string;\n text: string;\n attachments?: { name: string; localPath: string }[];\n threadTs?: string;\n}\n\nexport interface ChatToolResult {\n toolName: string;\n label?: string;\n args?: Record<string, unknown>;\n result: string;\n isError: boolean;\n durationMs: number;\n}\n\n/**\n * Derived from the run status rather than restated, so a new terminal status\n * in the harness reaches the dashboard instead of silently rendering as a\n * status the marker tables never learned about.\n */\nexport type SubagentProgressStatus = SubagentRunStatus | \"pending\" | \"running\" | \"skipped\";\n\nexport interface SubagentProgressNode {\n id: string;\n label: string;\n status: SubagentProgressStatus;\n /** Profile the node ran under; the first thing to check when a run is ungrounded. */\n profile?: string;\n turns?: number;\n toolCalls?: number;\n toolCallCounts?: Record<string, number>;\n tokens?: number;\n costUsd?: number;\n durationMs?: number;\n /**\n * What the node is doing right now, for running nodes only.\n *\n * Without it a node reports nothing between \"started\" and \"finished\", so a\n * step that legitimately takes minutes is indistinguishable from a hang —\n * and when it does finish, there is no record of how it got there.\n */\n activity?: string;\n reason?: string;\n cleanupPending?: boolean;\n}\n\nexport interface SubagentProgressSnapshot {\n mode: \"single\" | \"parallel\" | \"dag\";\n nodes: SubagentProgressNode[];\n}\n\nexport interface TaskStatus {\n sessionKey: string;\n threadTs: string;\n acknowledgement: string;\n status:\n | \"running\"\n | \"stopping\"\n | \"completed\"\n | \"aborted\"\n | \"failed\"\n | \"declined\"\n | \"queued\"\n | \"unknown\";\n currentTool?: string;\n observedAt: string;\n endedAt?: string;\n}\n\nexport interface ConversationResponder {\n /** Admit independent work; returns its platform session reference, never waits for completion. */\n startTask?(message: string, task: string): Promise<string>;\n /** Post a fresh delivery notification after the final task response. */\n notifyCompletion?(): Promise<void>;\n /** Read-only task observations, scoped to the current conversation. */\n getTaskStatus?(sessionKey?: string): Promise<TaskStatus[]>;\n respond(text: string): Promise<void>;\n appendResponseDelta?(delta: string): Promise<void>;\n finishResponse?(finalText?: string): Promise<void>;\n replaceResponse(text: string, options?: { createOverflowLink?: () => string }): Promise<void>;\n /**\n * Override only to convert the subagent dashboard for a pipeline that is\n * not response-source Markdown (Telegram HTML). Absent, the harness composes\n * the Markdown dashboard — optionally followed by the final answer — through\n * `replaceResponse`.\n */\n replaceSubagentProgress?(progress: SubagentProgressSnapshot, finalText?: string): Promise<void>;\n /**\n * Spike: post the final answer as a fresh message under the identity of the\n * subagent profile that produced it, instead of appending it to the\n * in-progress message. Absent, or when the run does not resolve to exactly\n * one completed subagent profile, the harness keeps the single-message path.\n */\n respondAsRole?(profile: string, text: string): Promise<void>;\n respondDiagnostic(text: string, options?: { style?: \"muted\" | \"error\" }): Promise<void>;\n respondToolResult(result: ChatToolResult): Promise<void>;\n setTyping(isTyping: boolean): Promise<void>;\n setWorking(working: boolean): Promise<void>;\n uploadFile(filePath: string, title?: string): Promise<void>;\n /**\n * React to the message that triggered this run with an emoji short name\n * (no colons). Optional: platforms/contexts without reaction support omit\n * it, and callers must handle its absence.\n */\n react?(emoji: string): Promise<void>;\n deleteResponse(): Promise<void>;\n}\n\nexport interface MessagingInfo {\n name: string;\n /** Stable platform workspace/team identity when the adapter has one. */\n workspaceId?: string;\n formattingGuide: string;\n channels: { id: string; name: string }[];\n users: { id: string; userName: string; displayName: string }[];\n /**\n * Trust boundary for ambient credentials and host-side MCP capabilities.\n * Built-in product paths normalize omission to `membership`; open-trigger\n * platforms set this explicitly so policy does not key off platform names.\n */\n trustModel?: PlatformTrustModel;\n diagnostics?: {\n showUsageSummary?: boolean;\n };\n}\n\n/**\n * A platform-agnostic event (message/mention) that triggers the agent.\n */\nexport interface ConversationEvent {\n type: string;\n /** Canonical identity created by the platform adapter at intake. */\n address: OfficeAddress;\n /** @deprecated Raw platform identifier; valid only at adapter I/O seams. */\n conversationId: string;\n /** Optional alternate conversation identity used for vault routing. */\n vaultConversationId?: string;\n /** Cross-platform conversation shape: direct message vs shared space */\n conversationKind: ConversationKind;\n /** Message timestamp or ID as string */\n ts: string;\n /** Parent message ID for threaded replies (optional) */\n thread_ts?: string;\n /** User ID */\n user: string;\n /** Message text (already stripped of bot mentions) */\n text: string;\n /** Downloaded attachments */\n attachments?: { name: string; localPath: string }[];\n /** Platform-computed session key; overrides default conversationId:thread_ts computation */\n sessionKey?: string;\n}\n\n/**\n * Minimum interface that every platform bot must implement,\n * used by the central handler in main.ts and by EventsWatcher.\n */\nexport interface MessagingBot {\n start(): Promise<void>;\n /** Stop accepting new platform events and wait for intake already in flight. */\n stop(): Promise<void>;\n postMessage(channel: string, text: string): Promise<string>;\n updateMessage(channel: string, ts: string, text: string): Promise<void>;\n /**\n * Add an emoji reaction to a message. `emoji` is a platform-agnostic short\n * name without colons (e.g. \"eyes\", \"white_check_mark\"). Optional so\n * adapters adopt it incrementally; callers must handle its absence.\n */\n addReaction?(channel: string, messageTs: string, emoji: string): Promise<void>;\n /**\n * Upload a host-side file into a conversation. Optional so adapters adopt\n * it incrementally; callers must handle its absence. Existing adapter\n * implementations (Slack/Discord/Telegram) already match this shape.\n */\n uploadFile?(channel: string, filePath: string, title?: string): Promise<void>;\n /**\n * Post into a platform thread. Optional so adapters adopt it incrementally;\n * callers must handle its absence.\n */\n postInThread?(channel: string, threadTs: string, text: string): Promise<string>;\n /**\n * Open (or resolve) the direct-message conversation with a user, returning\n * its conversation id — usable with `postMessage`. Optional capability.\n */\n openDirectConversation?(userId: string): Promise<string>;\n /**\n * Fetch recent messages from a conversation, oldest first. Optional\n * capability; adapters may cap `limit` below what the caller asks for.\n */\n fetchHistory?(\n channel: string,\n options?: PlatformHistoryOptions,\n ): Promise<PlatformHistoryMessage[]>;\n /** List the platform workspace's active users. Optional capability. */\n listUsers?(): Promise<PlatformUserInfo[]>;\n enqueueEvent(event: ConversationEvent): boolean;\n getMessagingInfo(): MessagingInfo;\n postPrivate?(conversationId: string, userId: string, text: string): Promise<void>;\n postPrivateDiagnostic?(\n conversationId: string,\n userId: string,\n text: string,\n options?: { style?: \"muted\" | \"error\" },\n ): Promise<void>;\n}\n\n/** Filters for a platform conversation-history fetch. */\nexport interface PlatformHistoryOptions {\n /** Only messages strictly newer than this platform message id/timestamp. */\n oldest?: string;\n /** Maximum number of messages to return (adapters may cap this lower). */\n limit?: number;\n /**\n * Read the replies inside this thread instead of the conversation's\n * top-level messages. The thread parent itself is not returned — the result\n * is the replies to it. Adapters without threads ignore this.\n */\n threadTs?: string;\n}\n\n/** One platform message returned by a history fetch. */\nexport interface PlatformHistoryMessage {\n ts: string;\n threadTs?: string;\n userId?: string;\n userName?: string;\n text: string;\n isBot: boolean;\n}\n\n/** One platform user returned by a workspace user listing. */\nexport interface PlatformUserInfo {\n id: string;\n userName: string;\n displayName: string;\n isBot: boolean;\n}\n\n/** Normalized platform data and reply hook for one event. */\nexport interface ConversationContext {\n /** Canonical identity for the office handling this turn. */\n address: OfficeAddress;\n message: ConversationMessage;\n responder: ConversationResponder;\n platform: MessagingInfo;\n}\n\nexport interface RunningSession {\n /** The office this run belongs to; two platforms may share a raw id. */\n address: OfficeAddress;\n sessionKey: string;\n startedAt: number;\n lastActivityAt?: number;\n currentTool?: string;\n stopping?: boolean;\n}\n\nexport interface HandleNewCommandOptions {\n sessionKey: string;\n conversationId: string;\n bot: MessagingBot;\n message: ConversationMessage;\n}\n\n/**\n * Runtime state is addressed by an office plus that office's platform session\n * reference. The session key alone is a platform value and is not unique\n * across platforms, so every session-scoped call carries its `OfficeAddress`.\n */\nexport interface MessagingEventHandler {\n isRunning(address: OfficeAddress, sessionKey: string): boolean;\n getRunningSessions(): RunningSession[];\n handleEvent(\n event: ConversationEvent,\n bot: MessagingBot,\n context: ConversationContext,\n ): Promise<void>;\n handleStop(\n address: OfficeAddress,\n sessionKey: string,\n bot: MessagingBot,\n replyThreadTs?: string,\n ): Promise<void>;\n /** Returns false when idle; accepted controls bypass the normal run queue. */\n steer?(message: ConversationMessage): Promise<boolean>;\n forceStop(address: OfficeAddress, sessionKey: string): void;\n handleNewCommand(options: HandleNewCommandOptions): Promise<void>;\n}\n\n// ── agent ─────────────────────────────────────────────────────────────────────\n\nexport interface PiAgentWrapper {\n steer?(message: ConversationMessage): Promise<boolean>;\n syncChatHistory(currentMessageId?: string): Promise<void>;\n run(\n message: ConversationMessage,\n responder: ConversationResponder,\n platform: MessagingInfo,\n ): Promise<{ stopReason: string; errorMessage?: string }>;\n abort(): void;\n getCurrentStep(): { toolName?: string; label?: string } | undefined;\n dispose(): Promise<void>;\n}\n\n// ── config ────────────────────────────────────────────────────────────────────\n\n/**\n * Office visibility (ADR 0008): public offices may be read by every office and\n * write shared knowledge; private ones are visible only to themselves.\n */\nexport type WorkspaceVisibility = \"public\" | \"private\";\n\nexport interface SandboxSettings {\n cpus?: string;\n memory?: string;\n boost?: { cpus?: string; memory?: string };\n defaultSharedVault?: string;\n}\n\nexport interface AgentConfig {\n provider: string;\n model: string;\n thinkingLevel: ThinkingLevel;\n sentryDsn?: string;\n sandbox?: SandboxSettings;\n slack?: {\n replyMode?: \"top-level\" | \"thread\";\n };\n /**\n * MCP servers available to this scope, keyed by server name. Global and\n * conversation entries merge per key (conversation wins); an entry with\n * `disabled: true` turns off the inherited server. `open-connector` is\n * filled in from the deployment default when undeclared. See `src/harness`.\n */\n mcpServers?: Record<string, McpServerConfig>;\n}\n\n// ── context ───────────────────────────────────────────────────────────────────\n\n/**\n * Platform conversation history entry from log.jsonl.\n */\nexport interface ConversationLogMessage {\n date?: string;\n ts?: string;\n threadTs?: string;\n user?: string;\n userName?: string;\n text?: string;\n isMessagingBot?: boolean;\n}\n\n// ── execution-resolver ────────────────────────────────────────────────────────\n\nexport interface ActorContext {\n /** Canonical office identity used by vault and execution policy. */\n address: OfficeAddress;\n userId: string;\n /** From MessagingInfo.trustModel; vault policy uses this, not platform name. */\n trustModel?: PlatformTrustModel;\n}\n\n// ── log ───────────────────────────────────────────────────────────────────────\n\nexport interface LogContext {\n conversationId: string;\n userName?: string;\n conversationName?: string;\n sessionId?: string;\n}\n\n// ── portal shell (src/adapters/web/portal-shell.ts) ────────────────────────────────────\n\ntype PortalView = \"admin\" | \"session\" | \"vault\";\n\nexport interface PortalShellOptions {\n activeView: PortalView;\n pageTitle: string;\n identity?: {\n primary: string;\n secondary?: string;\n };\n conversationSwitcher?: {\n currentId: string;\n options?: Array<{ id: string; label: string; running?: boolean }>;\n };\n navLinks?: Partial<Record<PortalView, string>>;\n body: string;\n extraStyles?: string;\n inlineScript?: string;\n extraHead?: string;\n bodyAttributes?: Record<string, string>;\n}\n\n// ── provisioner ───────────────────────────────────────────────────────────────\n\n/** Rewrites one Docker bind spec (`src:dst[:ro]`) during layout migration. */\nexport type ContainerBindTranslator = (bindSpec: string) => string;\n\nexport interface ContainerMount {\n source: string;\n target: string;\n /**\n * Mount without write access. Used for shared content an isolated runtime\n * may read but must not modify. Absent means read-write.\n */\n readOnly?: boolean;\n}\n\nexport interface ResourceLimits {\n cpus?: string;\n memory?: string;\n}\n\nexport interface SandboxLimitStatus {\n limits?: ResourceLimits;\n boosted: boolean;\n}\n\nexport interface SandboxResourceController {\n boost(key: string): Promise<SandboxLimitStatus>;\n setLimits(key: string, limits: ResourceLimits): Promise<SandboxLimitStatus>;\n getLimitStatus(key: string): SandboxLimitStatus;\n getDefaultLimits(): ResourceLimits | undefined;\n getBoostLimits(): ResourceLimits | undefined;\n}\n\nexport interface ProvisionOptions {\n containerName?: string;\n mounts?: ContainerMount[];\n conversationId?: string;\n}\n\nexport interface DockerContainerManagerOptions {\n limits?: ResourceLimits;\n boostLimits?: ResourceLimits;\n execFileImpl?: ExecFileAsync;\n}\n\nexport interface ExecutionPlan {\n credentialKey: string;\n resourceKey: string;\n sandboxConfig: SandboxConfig;\n env?: Record<string, string>;\n mounts: ContainerMount[];\n}\n\n// ── store ─────────────────────────────────────────────────────────────────────\n\nexport interface Attachment {\n original: string;\n localPath: string;\n}\n\n// ── shared implementation contracts ─────────────────────────────────────────\n\ninterface EnvVarSpec {\n name: string;\n required?: boolean;\n secret?: boolean;\n deploy?: boolean;\n doc: string;\n}\n\n/** The onboarding wizard's LLM answer, applied to the settings template. */\nexport interface OnboardLlmChoice {\n provider: string;\n model: string;\n}\n\nexport interface EnvGroup {\n key: string;\n title: string;\n kind: \"platform\" | \"feature\";\n vars: EnvVarSpec[];\n anyOf?: readonly string[];\n doc?: string;\n}\n\nexport interface RunnerCacheControl {\n switchConversationModel(address: OfficeAddress, provider: string, model: string): boolean;\n /** Clear the office's cached runner for a non-model settings change; false while busy. */\n refreshConversationEnvironment(address: OfficeAddress): boolean;\n}\n\nexport interface GlobalRunnerCacheControl {\n refreshAllConversations(): { busy: OfficeAddress[] };\n}\n\nexport type SettingsApplyResult =\n | { ok: true; runtimeSwitched: boolean | null }\n | { ok: false; reason: \"busy\" };\n\nexport interface CreateRunnerOptions {\n sandboxConfig: SandboxConfig;\n sessionKey: string;\n /** The Conversation office this runner serves; identity and layout derive from it. */\n office: Office;\n /**\n * Fixed trust boundary for this office. It is not part of runner cache\n * identity; changing it requires runner replacement, not another cache entry.\n */\n trustModel: PlatformTrustModel;\n /** Platform workspace/team identity used by host-side integration provisioning. */\n platformWorkspaceId?: string;\n /** Deployment default for the `open-connector` MCP entry; settings may override it. */\n openConnector?: McpServerConfig;\n /** Scheduler notified by the office event store after each admitted mutation. */\n eventScheduler?: EventScheduleSink;\n sessionScope: ResolvedSessionScope;\n /** Cancels construction during process shutdown; acquired resources still roll back before rejection. */\n signal?: AbortSignal;\n vaultManager?: VaultManager;\n provisioner?: DockerContainerManager;\n resourceController?: SandboxResourceController;\n sessionView?: {\n tokenStore: SessionViewTokenStoreLike;\n portalBaseUrl?: string;\n };\n platformToolPackFactories?: readonly PlatformToolPackFactory[];\n models?: MikanModels;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAatC,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { SubagentRunStatus } from \"./harness/types.js\";\nimport type { SessionViewTokenStoreLike } from \"./adapters/commands/types.js\";\nimport type { MikanModels } from \"./harness/models.js\";\nimport type { McpServerConfig } from \"./harness/types.js\";\nimport type { EventScheduleSink } from \"./events/index.js\";\nimport type { Office } from \"./office/types.js\";\nimport type { DockerContainerManager } from \"./sandbox/provisioner.js\";\nimport type { SandboxConfig } from \"./sandbox/types.js\";\nimport type { ResolvedSessionScope } from \"./sessions/types.js\";\nimport type { PlatformToolPackFactory } from \"./harness/tools/types.js\";\nimport type { VaultManager } from \"./vault/types.js\";\n\nconst execFileAsync = promisify(execFile);\ntype ExecFileAsync = typeof execFileAsync;\n\n// ── adapter ───────────────────────────────────────────────────────────────────\n\nexport type ConversationKind = \"direct\" | \"shared\";\n\nexport type PlatformName = \"slack\" | \"discord\" | \"telegram\" | \"github\";\n\n/** Canonical platform-plus-raw identifier for one conversation office. */\nexport interface OfficeAddress {\n readonly platform: PlatformName;\n readonly conversationId: string;\n}\n\n/** Stable, filesystem-safe identity derived from an OfficeAddress. */\nexport type OfficeKey = string & { readonly __brand: \"OfficeKey\" };\n\nexport type OfficeMigrationStatus = \"needs-owner\" | \"prepared\" | \"moving\" | \"committed\" | \"failed\";\n\nexport interface OfficeMigrationRecord {\n readonly rawConversationId: string;\n readonly sourceDir: string;\n readonly workspaceRoot: string;\n readonly ownerPlatform?: PlatformName;\n readonly targetDir?: string;\n readonly status: OfficeMigrationStatus;\n readonly error?: string;\n readonly updatedAt: string;\n}\n\n/**\n * Directory entry for one conversation office. The workspace dir name stops\n * carrying the raw platform id once the ADR 0005 layout migration lands, so\n * the registry is the durable raw-id ↔ office mapping used for enumeration.\n */\nexport interface OfficeRecord {\n readonly platform: PlatformName;\n readonly conversationId: string;\n readonly recordedAt: string;\n}\n\nexport interface OfficeRegistryState {\n readonly version: 1;\n readonly enabledPlatforms: readonly PlatformName[];\n readonly offices: readonly OfficeRecord[];\n readonly migrations: readonly OfficeMigrationRecord[];\n}\n\nexport interface OfficeMigrationPreparation {\n readonly rawConversationId: string;\n readonly sourceDir: string;\n readonly workspaceRoot: string;\n readonly ownerPlatform?: PlatformName;\n}\n\n/**\n * Who can drive conversations on a platform — gates ambient credential policy.\n *\n * - `membership`: only invited workspace/server members (Slack/Discord/Telegram).\n * Safe to copy `sandbox.defaultSharedVault` into new conversation vaults.\n * - `open-trigger`: broader trigger surface (e.g. GitHub repo writers on public\n * issues/PRs). Ambient shared vault must not apply; use host-side platform\n * identity or an explicitly provisioned vault.\n */\nexport type PlatformTrustModel = \"membership\" | \"open-trigger\";\n\nexport interface ConversationMessage {\n id: string;\n /** Canonical identity of the conversation office. */\n address: OfficeAddress;\n /** @deprecated Use address.conversationId except at platform I/O seams. */\n conversationId?: string;\n sessionKey: string;\n conversationKind: ConversationKind;\n userId: string;\n userName?: string;\n text: string;\n attachments?: { name: string; localPath: string }[];\n threadTs?: string;\n}\n\nexport interface ChatToolResult {\n toolName: string;\n label?: string;\n args?: Record<string, unknown>;\n result: string;\n isError: boolean;\n durationMs: number;\n}\n\n/**\n * Derived from the run status rather than restated, so a new terminal status\n * in the harness reaches the dashboard instead of silently rendering as a\n * status the marker tables never learned about.\n */\nexport type SubagentProgressStatus = SubagentRunStatus | \"pending\" | \"running\" | \"skipped\";\n\nexport interface SubagentProgressNode {\n id: string;\n label: string;\n status: SubagentProgressStatus;\n /** Profile the node ran under; the first thing to check when a run is ungrounded. */\n profile?: string;\n turns?: number;\n toolCalls?: number;\n toolCallCounts?: Record<string, number>;\n tokens?: number;\n costUsd?: number;\n durationMs?: number;\n /**\n * What the node is doing right now, for running nodes only.\n *\n * Without it a node reports nothing between \"started\" and \"finished\", so a\n * step that legitimately takes minutes is indistinguishable from a hang —\n * and when it does finish, there is no record of how it got there.\n */\n activity?: string;\n reason?: string;\n cleanupPending?: boolean;\n}\n\nexport interface SubagentProgressSnapshot {\n mode: \"single\" | \"parallel\" | \"dag\";\n nodes: SubagentProgressNode[];\n}\n\nexport interface TaskStatus {\n sessionKey: string;\n threadTs: string;\n acknowledgement: string;\n status:\n | \"running\"\n | \"stopping\"\n | \"completed\"\n | \"aborted\"\n | \"failed\"\n | \"declined\"\n | \"queued\"\n | \"unknown\";\n currentTool?: string;\n observedAt: string;\n endedAt?: string;\n}\n\nexport interface ConversationResponder {\n /** Admit independent work; returns its platform session reference, never waits for completion. */\n startTask?(message: string, task: string): Promise<string>;\n /** Post a fresh delivery notification after the final task response. */\n notifyCompletion?(): Promise<void>;\n /** Read-only task observations, scoped to the current conversation. */\n getTaskStatus?(sessionKey?: string): Promise<TaskStatus[]>;\n respond(text: string): Promise<void>;\n appendResponseDelta?(delta: string): Promise<void>;\n finishResponse?(finalText?: string): Promise<void>;\n replaceResponse(text: string, options?: { createOverflowLink?: () => string }): Promise<void>;\n /**\n * Override only to convert the subagent dashboard for a pipeline that is\n * not response-source Markdown (Telegram HTML). Absent, the harness composes\n * the Markdown dashboard — optionally followed by the final answer — through\n * `replaceResponse`.\n */\n replaceSubagentProgress?(progress: SubagentProgressSnapshot, finalText?: string): Promise<void>;\n /**\n * Spike: post the final answer as a fresh message under the identity of the\n * subagent profile that produced it, instead of appending it to the\n * in-progress message. Absent, or when the run does not resolve to exactly\n * one completed subagent profile, the harness keeps the single-message path.\n */\n respondAsRole?(profile: string, text: string): Promise<void>;\n respondDiagnostic(text: string, options?: { style?: \"muted\" | \"error\" }): Promise<void>;\n respondToolResult(result: ChatToolResult): Promise<void>;\n setTyping(isTyping: boolean): Promise<void>;\n setWorking(working: boolean): Promise<void>;\n uploadFile(filePath: string, title?: string): Promise<void>;\n /**\n * React to the message that triggered this run with an emoji short name\n * (no colons). Optional: platforms/contexts without reaction support omit\n * it, and callers must handle its absence.\n */\n react?(emoji: string): Promise<void>;\n deleteResponse(): Promise<void>;\n}\n\nexport interface MessagingInfo {\n name: string;\n /** Stable platform workspace/team identity when the adapter has one. */\n workspaceId?: string;\n formattingGuide: string;\n channels: { id: string; name: string }[];\n users: { id: string; userName: string; displayName: string }[];\n /**\n * Trust boundary for ambient credentials and host-side MCP capabilities.\n * Built-in product paths normalize omission to `membership`; open-trigger\n * platforms set this explicitly so policy does not key off platform names.\n */\n trustModel?: PlatformTrustModel;\n diagnostics?: {\n showUsageSummary?: boolean;\n };\n}\n\n/**\n * A platform-agnostic event (message/mention) that triggers the agent.\n */\nexport interface ConversationEvent {\n type: string;\n /** Canonical identity created by the platform adapter at intake. */\n address: OfficeAddress;\n /** @deprecated Raw platform identifier; valid only at adapter I/O seams. */\n conversationId: string;\n /** Optional alternate conversation identity used for vault routing. */\n vaultConversationId?: string;\n /** Cross-platform conversation shape: direct message vs shared space */\n conversationKind: ConversationKind;\n /** Message timestamp or ID as string */\n ts: string;\n /** Parent message ID for threaded replies (optional) */\n thread_ts?: string;\n /** User ID */\n user: string;\n /** Message text (already stripped of bot mentions) */\n text: string;\n /** Downloaded attachments */\n attachments?: { name: string; localPath: string }[];\n /** Platform-computed session key; overrides default conversationId:thread_ts computation */\n sessionKey?: string;\n}\n\n/**\n * Minimum interface that every platform bot must implement,\n * used by the central handler in main.ts and by EventsWatcher.\n */\nexport interface MessagingBot {\n start(): Promise<void>;\n /** Stop accepting new platform events and wait for intake already in flight. */\n stop(): Promise<void>;\n postMessage(channel: string, text: string): Promise<string>;\n updateMessage(channel: string, ts: string, text: string): Promise<void>;\n /**\n * Add an emoji reaction to a message. `emoji` is a platform-agnostic short\n * name without colons (e.g. \"eyes\", \"white_check_mark\"). Optional so\n * adapters adopt it incrementally; callers must handle its absence.\n */\n addReaction?(channel: string, messageTs: string, emoji: string): Promise<void>;\n /**\n * Upload a host-side file into a conversation. Optional so adapters adopt\n * it incrementally; callers must handle its absence. Existing adapter\n * implementations (Slack/Discord/Telegram) already match this shape.\n */\n uploadFile?(channel: string, filePath: string, title?: string): Promise<void>;\n /**\n * Post into a platform thread. Optional so adapters adopt it incrementally;\n * callers must handle its absence.\n */\n postInThread?(channel: string, threadTs: string, text: string): Promise<string>;\n /**\n * Open (or resolve) the direct-message conversation with a user, returning\n * its conversation id — usable with `postMessage`. Optional capability.\n */\n openDirectConversation?(userId: string): Promise<string>;\n /**\n * Fetch recent messages from a conversation, oldest first. Optional\n * capability; adapters may cap `limit` below what the caller asks for.\n */\n fetchHistory?(\n channel: string,\n options?: PlatformHistoryOptions,\n ): Promise<PlatformHistoryMessage[]>;\n /** List the platform workspace's active users. Optional capability. */\n listUsers?(): Promise<PlatformUserInfo[]>;\n /**\n * Record the bot's own outbound message in the conversation's human-readable\n * `log.jsonl`, mirroring the entry `logToFile` would write for an agent\n * reply. Optional so adapters adopt it incrementally; callers that skip it\n * leave that message invisible to `log.jsonl` history (and to the agent's\n * own greps over it) even though the platform delivered it.\n */\n logBotResponse?(channel: string, text: string, ts: string, threadTs?: string): void;\n enqueueEvent(event: ConversationEvent): boolean;\n getMessagingInfo(): MessagingInfo;\n postPrivate?(conversationId: string, userId: string, text: string): Promise<void>;\n postPrivateDiagnostic?(\n conversationId: string,\n userId: string,\n text: string,\n options?: { style?: \"muted\" | \"error\" },\n ): Promise<void>;\n}\n\n/** Filters for a platform conversation-history fetch. */\nexport interface PlatformHistoryOptions {\n /** Only messages strictly newer than this platform message id/timestamp. */\n oldest?: string;\n /** Maximum number of messages to return (adapters may cap this lower). */\n limit?: number;\n /**\n * Read the replies inside this thread instead of the conversation's\n * top-level messages. The thread parent itself is not returned — the result\n * is the replies to it. Adapters without threads ignore this.\n */\n threadTs?: string;\n}\n\n/** One platform message returned by a history fetch. */\nexport interface PlatformHistoryMessage {\n ts: string;\n threadTs?: string;\n userId?: string;\n userName?: string;\n text: string;\n isBot: boolean;\n}\n\n/** One platform user returned by a workspace user listing. */\nexport interface PlatformUserInfo {\n id: string;\n userName: string;\n displayName: string;\n isBot: boolean;\n}\n\n/** Normalized platform data and reply hook for one event. */\nexport interface ConversationContext {\n /** Canonical identity for the office handling this turn. */\n address: OfficeAddress;\n message: ConversationMessage;\n responder: ConversationResponder;\n platform: MessagingInfo;\n}\n\nexport interface RunningSession {\n /** The office this run belongs to; two platforms may share a raw id. */\n address: OfficeAddress;\n sessionKey: string;\n startedAt: number;\n lastActivityAt?: number;\n currentTool?: string;\n stopping?: boolean;\n}\n\nexport interface HandleNewCommandOptions {\n sessionKey: string;\n conversationId: string;\n bot: MessagingBot;\n message: ConversationMessage;\n}\n\n/**\n * Runtime state is addressed by an office plus that office's platform session\n * reference. The session key alone is a platform value and is not unique\n * across platforms, so every session-scoped call carries its `OfficeAddress`.\n */\nexport interface MessagingEventHandler {\n isRunning(address: OfficeAddress, sessionKey: string): boolean;\n getRunningSessions(): RunningSession[];\n handleEvent(\n event: ConversationEvent,\n bot: MessagingBot,\n context: ConversationContext,\n ): Promise<void>;\n handleStop(\n address: OfficeAddress,\n sessionKey: string,\n bot: MessagingBot,\n replyThreadTs?: string,\n ): Promise<void>;\n /** Returns false when idle; accepted controls bypass the normal run queue. */\n steer?(message: ConversationMessage): Promise<boolean>;\n forceStop(address: OfficeAddress, sessionKey: string): void;\n handleNewCommand(options: HandleNewCommandOptions): Promise<void>;\n}\n\n// ── agent ─────────────────────────────────────────────────────────────────────\n\nexport interface PiAgentWrapper {\n steer?(message: ConversationMessage): Promise<boolean>;\n syncChatHistory(currentMessageId?: string): Promise<void>;\n run(\n message: ConversationMessage,\n responder: ConversationResponder,\n platform: MessagingInfo,\n ): Promise<{ stopReason: string; errorMessage?: string }>;\n abort(): void;\n getCurrentStep(): { toolName?: string; label?: string } | undefined;\n dispose(): Promise<void>;\n}\n\n// ── config ────────────────────────────────────────────────────────────────────\n\n/**\n * Office visibility (ADR 0008): public offices may be read by every office and\n * write shared knowledge; private ones are visible only to themselves.\n */\nexport type WorkspaceVisibility = \"public\" | \"private\";\n\nexport interface SandboxSettings {\n cpus?: string;\n memory?: string;\n boost?: { cpus?: string; memory?: string };\n defaultSharedVault?: string;\n}\n\nexport interface AgentConfig {\n provider: string;\n model: string;\n thinkingLevel: ThinkingLevel;\n sentryDsn?: string;\n sandbox?: SandboxSettings;\n slack?: {\n replyMode?: \"top-level\" | \"thread\";\n };\n /**\n * MCP servers available to this scope, keyed by server name. Global and\n * conversation entries merge per key (conversation wins); an entry with\n * `disabled: true` turns off the inherited server. `open-connector` is\n * filled in from the deployment default when undeclared. See `src/harness`.\n */\n mcpServers?: Record<string, McpServerConfig>;\n}\n\n// ── context ───────────────────────────────────────────────────────────────────\n\n/**\n * Platform conversation history entry from log.jsonl.\n */\nexport interface ConversationLogMessage {\n date?: string;\n ts?: string;\n threadTs?: string;\n user?: string;\n userName?: string;\n text?: string;\n isMessagingBot?: boolean;\n}\n\n// ── execution-resolver ────────────────────────────────────────────────────────\n\nexport interface ActorContext {\n /** Canonical office identity used by vault and execution policy. */\n address: OfficeAddress;\n userId: string;\n /** From MessagingInfo.trustModel; vault policy uses this, not platform name. */\n trustModel?: PlatformTrustModel;\n}\n\n// ── log ───────────────────────────────────────────────────────────────────────\n\nexport interface LogContext {\n conversationId: string;\n userName?: string;\n conversationName?: string;\n sessionId?: string;\n}\n\n// ── portal shell (src/adapters/web/portal-shell.ts) ────────────────────────────────────\n\ntype PortalView = \"admin\" | \"session\" | \"vault\";\n\nexport interface PortalShellOptions {\n activeView: PortalView;\n pageTitle: string;\n identity?: {\n primary: string;\n secondary?: string;\n };\n conversationSwitcher?: {\n currentId: string;\n options?: Array<{ id: string; label: string; running?: boolean }>;\n };\n navLinks?: Partial<Record<PortalView, string>>;\n body: string;\n extraStyles?: string;\n inlineScript?: string;\n extraHead?: string;\n bodyAttributes?: Record<string, string>;\n}\n\n// ── provisioner ───────────────────────────────────────────────────────────────\n\n/** Rewrites one Docker bind spec (`src:dst[:ro]`) during layout migration. */\nexport type ContainerBindTranslator = (bindSpec: string) => string;\n\nexport interface ContainerMount {\n source: string;\n target: string;\n /**\n * Mount without write access. Used for shared content an isolated runtime\n * may read but must not modify. Absent means read-write.\n */\n readOnly?: boolean;\n}\n\nexport interface ResourceLimits {\n cpus?: string;\n memory?: string;\n}\n\nexport interface SandboxLimitStatus {\n limits?: ResourceLimits;\n boosted: boolean;\n}\n\nexport interface SandboxResourceController {\n boost(key: string): Promise<SandboxLimitStatus>;\n setLimits(key: string, limits: ResourceLimits): Promise<SandboxLimitStatus>;\n getLimitStatus(key: string): SandboxLimitStatus;\n getDefaultLimits(): ResourceLimits | undefined;\n getBoostLimits(): ResourceLimits | undefined;\n}\n\nexport interface ProvisionOptions {\n containerName?: string;\n mounts?: ContainerMount[];\n conversationId?: string;\n}\n\nexport interface DockerContainerManagerOptions {\n limits?: ResourceLimits;\n boostLimits?: ResourceLimits;\n execFileImpl?: ExecFileAsync;\n}\n\nexport interface ExecutionPlan {\n credentialKey: string;\n resourceKey: string;\n sandboxConfig: SandboxConfig;\n env?: Record<string, string>;\n mounts: ContainerMount[];\n}\n\n// ── store ─────────────────────────────────────────────────────────────────────\n\nexport interface Attachment {\n original: string;\n localPath: string;\n}\n\n// ── shared implementation contracts ─────────────────────────────────────────\n\ninterface EnvVarSpec {\n name: string;\n required?: boolean;\n secret?: boolean;\n deploy?: boolean;\n doc: string;\n}\n\n/** The onboarding wizard's LLM answer, applied to the settings template. */\nexport interface OnboardLlmChoice {\n provider: string;\n model: string;\n}\n\nexport interface EnvGroup {\n key: string;\n title: string;\n kind: \"platform\" | \"feature\";\n vars: EnvVarSpec[];\n anyOf?: readonly string[];\n doc?: string;\n}\n\nexport interface RunnerCacheControl {\n switchConversationModel(address: OfficeAddress, provider: string, model: string): boolean;\n /** Clear the office's cached runner for a non-model settings change; false while busy. */\n refreshConversationEnvironment(address: OfficeAddress): boolean;\n}\n\nexport interface GlobalRunnerCacheControl {\n refreshAllConversations(): { busy: OfficeAddress[] };\n}\n\nexport type SettingsApplyResult =\n | { ok: true; runtimeSwitched: boolean | null }\n | { ok: false; reason: \"busy\" };\n\nexport interface CreateRunnerOptions {\n sandboxConfig: SandboxConfig;\n sessionKey: string;\n /** The Conversation office this runner serves; identity and layout derive from it. */\n office: Office;\n /**\n * Fixed trust boundary for this office. It is not part of runner cache\n * identity; changing it requires runner replacement, not another cache entry.\n */\n trustModel: PlatformTrustModel;\n /** Platform workspace/team identity used by host-side integration provisioning. */\n platformWorkspaceId?: string;\n /** Deployment default for the `open-connector` MCP entry; settings may override it. */\n openConnector?: McpServerConfig;\n /** Scheduler notified by the office event store after each admitted mutation. */\n eventScheduler?: EventScheduleSink;\n sessionScope: ResolvedSessionScope;\n /** Cancels construction during process shutdown; acquired resources still roll back before rejection. */\n signal?: AbortSignal;\n vaultManager?: VaultManager;\n provisioner?: DockerContainerManager;\n resourceController?: SandboxResourceController;\n sessionView?: {\n tokenStore: SessionViewTokenStoreLike;\n portalBaseUrl?: string;\n };\n platformToolPackFactories?: readonly PlatformToolPackFactory[];\n models?: MikanModels;\n}\n"]}