@alisio/core 0.1.0-alpha.9 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/README.md +52 -7
  2. package/dist/agents/active.d.ts +99 -0
  3. package/dist/agents/active.js +218 -0
  4. package/dist/agents/capabilities.d.ts +26 -0
  5. package/dist/agents/capabilities.js +120 -0
  6. package/dist/agents/create-agent-skill.d.ts +11 -0
  7. package/dist/agents/create-agent-skill.js +60 -0
  8. package/dist/agents/definitions.d.ts +88 -0
  9. package/dist/agents/definitions.js +404 -0
  10. package/dist/agents/draft.d.ts +41 -0
  11. package/dist/agents/draft.js +133 -0
  12. package/dist/agents/service.d.ts +57 -0
  13. package/dist/agents/service.js +86 -0
  14. package/dist/agents/templates.d.ts +8 -0
  15. package/dist/agents/templates.js +102 -0
  16. package/dist/analysis/capabilities.d.ts +48 -0
  17. package/dist/analysis/capabilities.js +90 -0
  18. package/dist/analysis/data/csv.d.ts +46 -0
  19. package/dist/analysis/data/csv.js +240 -0
  20. package/dist/analysis/data/datasets.d.ts +132 -0
  21. package/dist/analysis/data/datasets.js +441 -0
  22. package/dist/analysis/data/describe.d.ts +27 -0
  23. package/dist/analysis/data/describe.js +103 -0
  24. package/dist/analysis/data/engine-client.d.ts +58 -0
  25. package/dist/analysis/data/engine-client.js +304 -0
  26. package/dist/analysis/data/engine-entry.d.ts +1 -0
  27. package/dist/analysis/data/engine-entry.js +59 -0
  28. package/dist/analysis/data/engine-source.d.ts +4 -0
  29. package/dist/analysis/data/engine-source.js +6 -0
  30. package/dist/analysis/data/engine-types.d.ts +86 -0
  31. package/dist/analysis/data/engine-types.js +7 -0
  32. package/dist/analysis/data/infer.d.ts +42 -0
  33. package/dist/analysis/data/infer.js +118 -0
  34. package/dist/analysis/data/ingest-worker.d.ts +17 -0
  35. package/dist/analysis/data/ingest-worker.js +365 -0
  36. package/dist/analysis/data/json.d.ts +19 -0
  37. package/dist/analysis/data/json.js +44 -0
  38. package/dist/analysis/data/query-worker.d.ts +12 -0
  39. package/dist/analysis/data/query-worker.js +75 -0
  40. package/dist/analysis/data/rows.d.ts +39 -0
  41. package/dist/analysis/data/rows.js +120 -0
  42. package/dist/analysis/data/sql-guard.d.ts +20 -0
  43. package/dist/analysis/data/sql-guard.js +129 -0
  44. package/dist/analysis/data/stats.d.ts +18 -0
  45. package/dist/analysis/data/stats.js +77 -0
  46. package/dist/analysis/install-hints.d.ts +33 -0
  47. package/dist/analysis/install-hints.js +144 -0
  48. package/dist/analysis/janitor.d.ts +60 -0
  49. package/dist/analysis/janitor.js +264 -0
  50. package/dist/analysis/jobs.d.ts +94 -0
  51. package/dist/analysis/jobs.js +165 -0
  52. package/dist/analysis/oci.d.ts +129 -0
  53. package/dist/analysis/oci.js +330 -0
  54. package/dist/analysis/python/sources.d.ts +2 -0
  55. package/dist/analysis/python/sources.js +10 -0
  56. package/dist/analysis/requirements.d.ts +32 -0
  57. package/dist/analysis/requirements.js +73 -0
  58. package/dist/analysis/rerun.d.ts +40 -0
  59. package/dist/analysis/rerun.js +136 -0
  60. package/dist/analysis/runtime-manager.d.ts +146 -0
  61. package/dist/analysis/runtime-manager.js +472 -0
  62. package/dist/analysis/status.d.ts +21 -0
  63. package/dist/analysis/status.js +52 -0
  64. package/dist/application.d.ts +105 -3
  65. package/dist/application.js +446 -18
  66. package/dist/artifacts/kinds.d.ts +35 -0
  67. package/dist/artifacts/kinds.js +177 -0
  68. package/dist/artifacts/publisher.d.ts +7 -0
  69. package/dist/artifacts/publisher.js +29 -0
  70. package/dist/artifacts/store.d.ts +119 -0
  71. package/dist/artifacts/store.js +581 -0
  72. package/dist/background/janitor.d.ts +22 -0
  73. package/dist/background/janitor.js +62 -0
  74. package/dist/background/mirror.d.ts +14 -0
  75. package/dist/background/mirror.js +41 -0
  76. package/dist/background/notify.d.ts +58 -0
  77. package/dist/background/notify.js +172 -0
  78. package/dist/background/output.d.ts +46 -0
  79. package/dist/background/output.js +179 -0
  80. package/dist/background/service.d.ts +137 -0
  81. package/dist/background/service.js +410 -0
  82. package/dist/background/store.d.ts +103 -0
  83. package/dist/background/store.js +195 -0
  84. package/dist/changelog/data.d.ts +6 -0
  85. package/dist/changelog/data.js +306 -0
  86. package/dist/changelog/index.d.ts +5 -0
  87. package/dist/changelog/index.js +7 -0
  88. package/dist/changelog/parse.d.ts +53 -0
  89. package/dist/changelog/parse.js +160 -0
  90. package/dist/commands/builtins.d.ts +10 -0
  91. package/dist/commands/builtins.js +161 -0
  92. package/dist/commands/catalog.d.ts +86 -0
  93. package/dist/commands/catalog.js +304 -0
  94. package/dist/config.d.ts +206 -6
  95. package/dist/config.js +426 -20
  96. package/dist/core/compaction.js +13 -2
  97. package/dist/core/contracts.d.ts +180 -3
  98. package/dist/core/opt-in.d.ts +12 -0
  99. package/dist/core/opt-in.js +12 -0
  100. package/dist/core/output-limit.d.ts +34 -0
  101. package/dist/core/output-limit.js +39 -0
  102. package/dist/core/run-stats.d.ts +16 -0
  103. package/dist/core/run-stats.js +8 -0
  104. package/dist/core/runner.d.ts +134 -4
  105. package/dist/core/runner.js +780 -138
  106. package/dist/core/timeout.d.ts +15 -0
  107. package/dist/core/timeout.js +61 -0
  108. package/dist/core/truncation.d.ts +30 -0
  109. package/dist/core/truncation.js +83 -0
  110. package/dist/goal/blockers.d.ts +45 -0
  111. package/dist/goal/blockers.js +51 -0
  112. package/dist/goal/budget.d.ts +24 -0
  113. package/dist/goal/budget.js +53 -0
  114. package/dist/goal/command.d.ts +36 -0
  115. package/dist/goal/command.js +98 -0
  116. package/dist/goal/format.d.ts +19 -0
  117. package/dist/goal/format.js +102 -0
  118. package/dist/goal/host.d.ts +29 -0
  119. package/dist/goal/host.js +42 -0
  120. package/dist/goal/index.d.ts +9 -0
  121. package/dist/goal/index.js +9 -0
  122. package/dist/goal/machine.d.ts +186 -0
  123. package/dist/goal/machine.js +344 -0
  124. package/dist/goal/prompts.d.ts +10 -0
  125. package/dist/goal/prompts.js +75 -0
  126. package/dist/goal/service.d.ts +113 -0
  127. package/dist/goal/service.js +273 -0
  128. package/dist/goal/store.d.ts +59 -0
  129. package/dist/goal/store.js +184 -0
  130. package/dist/index.d.ts +50 -5
  131. package/dist/index.js +49 -4
  132. package/dist/mcp/connector.js +38 -6
  133. package/dist/mcp/rich.d.ts +41 -0
  134. package/dist/mcp/rich.js +362 -0
  135. package/dist/permissions/modes.d.ts +72 -0
  136. package/dist/permissions/modes.js +98 -0
  137. package/dist/plan/exit-plan.d.ts +25 -0
  138. package/dist/plan/exit-plan.js +130 -0
  139. package/dist/plan/state.d.ts +102 -0
  140. package/dist/plan/state.js +165 -0
  141. package/dist/plugins/host.d.ts +34 -1
  142. package/dist/plugins/host.js +143 -9
  143. package/dist/providers/settings.d.ts +15 -0
  144. package/dist/providers/settings.js +38 -0
  145. package/dist/reload.d.ts +75 -0
  146. package/dist/reload.js +204 -0
  147. package/dist/resources/context.js +6 -1
  148. package/dist/runtime/access.d.ts +62 -0
  149. package/dist/runtime/access.js +115 -0
  150. package/dist/runtime/blobs.d.ts +51 -0
  151. package/dist/runtime/blobs.js +177 -0
  152. package/dist/runtime/diff.d.ts +23 -0
  153. package/dist/runtime/diff.js +154 -0
  154. package/dist/runtime/ids.d.ts +8 -0
  155. package/dist/runtime/ids.js +32 -0
  156. package/dist/runtime/paths.d.ts +11 -0
  157. package/dist/runtime/paths.js +17 -1
  158. package/dist/runtime/process.d.ts +22 -0
  159. package/dist/runtime/process.js +100 -15
  160. package/dist/runtime/sqlite.d.ts +2 -0
  161. package/dist/runtime/sqlite.js +18 -0
  162. package/dist/runtime/store.d.ts +91 -3
  163. package/dist/runtime/store.js +465 -11
  164. package/dist/runtime/zip.d.ts +24 -0
  165. package/dist/runtime/zip.js +126 -0
  166. package/dist/sessions/children.js +17 -1
  167. package/dist/sessions/side-questions.d.ts +57 -0
  168. package/dist/sessions/side-questions.js +161 -0
  169. package/dist/tools/analysis.d.ts +37 -0
  170. package/dist/tools/analysis.js +573 -0
  171. package/dist/tools/artifacts.d.ts +14 -0
  172. package/dist/tools/artifacts.js +143 -0
  173. package/dist/tools/background.d.ts +7 -0
  174. package/dist/tools/background.js +165 -0
  175. package/dist/tools/data.d.ts +7 -0
  176. package/dist/tools/data.js +160 -0
  177. package/dist/tools/execute.d.ts +5 -0
  178. package/dist/tools/execute.js +15 -3
  179. package/dist/tools/goal.d.ts +19 -0
  180. package/dist/tools/goal.js +126 -0
  181. package/dist/tools/search.d.ts +17 -3
  182. package/dist/tools/search.js +153 -0
  183. package/dist/tools/standard.d.ts +4 -1
  184. package/dist/tools/standard.js +99 -18
  185. package/dist/version.d.ts +5 -3
  186. package/dist/version.js +35 -6
  187. package/package.json +2 -2
@@ -0,0 +1,184 @@
1
+ import { isProcessAlive } from "../runtime/process.js";
2
+ import { GOAL_STATUSES, systemRestart } from "./machine.js";
3
+ const num = (value) => value === null || value === undefined ? undefined : Number(value);
4
+ const str = (value) => value === null || value === undefined ? undefined : String(value);
5
+ function parseEvidence(raw) {
6
+ if (typeof raw !== "string" || !raw)
7
+ return undefined;
8
+ try {
9
+ const value = JSON.parse(raw);
10
+ return Array.isArray(value) ? value : undefined;
11
+ }
12
+ catch {
13
+ return undefined;
14
+ }
15
+ }
16
+ export function goalFromRow(row) {
17
+ const status = String(row.status);
18
+ return {
19
+ sessionId: String(row.session),
20
+ goalId: str(row.goal_id) ?? String(row.session).slice(0, 8),
21
+ objective: String(row.objective),
22
+ status: GOAL_STATUSES.includes(status) ? status : "paused",
23
+ ...(str(row.reason) ? { reason: str(row.reason) } : {}),
24
+ ...(str(row.detail) ? { detail: str(row.detail) } : {}),
25
+ ...(str(row.summary) ? { summary: str(row.summary) } : {}),
26
+ ...(parseEvidence(row.evidence)
27
+ ? { evidence: parseEvidence(row.evidence) }
28
+ : {}),
29
+ epoch: Number(row.epoch ?? 1),
30
+ ...(num(row.token_budget) !== undefined
31
+ ? { tokenBudget: num(row.token_budget) }
32
+ : {}),
33
+ tokensUsed: Number(row.tokens_used ?? 0),
34
+ turnsUsed: Number(row.turns_used ?? 0),
35
+ maxTurns: Number(row.max_turns),
36
+ maxWallMs: Number(row.max_wall_ms),
37
+ activeMs: Number(row.active_ms ?? 0),
38
+ noToolStreak: Number(row.no_tool_streak ?? 0),
39
+ repeatStreak: Number(row.repeat_streak ?? 0),
40
+ ...(str(row.last_reply_hash) ? { lastReplyHash: str(row.last_reply_hash) } : {}),
41
+ blockedStreak: Number(row.blocked_streak ?? 0),
42
+ ...(str(row.blocked_run) ? { blockedRun: str(row.blocked_run) } : {}),
43
+ continuations: Number(row.continuations ?? 0),
44
+ ...(str(row.inflight) ? { inflight: str(row.inflight) } : {}),
45
+ ...(str(row.last_run_id) ? { lastRunId: str(row.last_run_id) } : {}),
46
+ kickoffSent: Number(row.kickoff_sent ?? 0) === 1,
47
+ ...(num(row.owner_pid) !== undefined ? { ownerPid: num(row.owner_pid) } : {}),
48
+ createdAt: Number(row.created_at),
49
+ updatedAt: Number(row.updated_at),
50
+ ...(num(row.completed_at) !== undefined
51
+ ? { completedAt: num(row.completed_at) }
52
+ : {}),
53
+ };
54
+ }
55
+ const COLUMNS = `session, goal_id, objective, status, reason, detail, summary, evidence, epoch,
56
+ token_budget, tokens_used, turns_used, max_turns, max_wall_ms, active_ms, no_tool_streak,
57
+ repeat_streak, last_reply_hash, blocked_streak, blocked_run, continuations, inflight,
58
+ last_run_id, kickoff_sent, owner_pid, created_at, updated_at, completed_at`;
59
+ export class GoalStore {
60
+ db;
61
+ constructor(db) {
62
+ this.db = db;
63
+ }
64
+ get(sessionId) {
65
+ const row = this.db.prepare("SELECT * FROM session_goals WHERE session=?").get(sessionId);
66
+ return row ? goalFromRow(row) : undefined;
67
+ }
68
+ /** Every goal that is `active` (restart recovery). */
69
+ active() {
70
+ return this.db
71
+ .prepare("SELECT * FROM session_goals WHERE status='active'")
72
+ .all()
73
+ .map(goalFromRow);
74
+ }
75
+ write(goal) {
76
+ this.db
77
+ .prepare(`INSERT INTO session_goals(${COLUMNS}) VALUES(${COLUMNS.split(",")
78
+ .map(() => "?")
79
+ .join(",")})
80
+ ON CONFLICT(session) DO UPDATE SET
81
+ goal_id=excluded.goal_id, objective=excluded.objective, status=excluded.status,
82
+ reason=excluded.reason, detail=excluded.detail, summary=excluded.summary,
83
+ evidence=excluded.evidence, epoch=excluded.epoch, token_budget=excluded.token_budget,
84
+ tokens_used=excluded.tokens_used, turns_used=excluded.turns_used,
85
+ max_turns=excluded.max_turns, max_wall_ms=excluded.max_wall_ms,
86
+ active_ms=excluded.active_ms, no_tool_streak=excluded.no_tool_streak,
87
+ repeat_streak=excluded.repeat_streak, last_reply_hash=excluded.last_reply_hash,
88
+ blocked_streak=excluded.blocked_streak, blocked_run=excluded.blocked_run,
89
+ continuations=excluded.continuations, inflight=excluded.inflight,
90
+ last_run_id=excluded.last_run_id, kickoff_sent=excluded.kickoff_sent,
91
+ owner_pid=excluded.owner_pid, updated_at=excluded.updated_at,
92
+ completed_at=excluded.completed_at`)
93
+ .run(goal.sessionId, goal.goalId, goal.objective, goal.status, goal.reason ?? null, goal.detail ?? null, goal.summary ?? null, goal.evidence?.length ? JSON.stringify(goal.evidence) : null, goal.epoch, goal.tokenBudget ?? null, goal.tokensUsed, goal.turnsUsed, goal.maxTurns, goal.maxWallMs, goal.activeMs, goal.noToolStreak, goal.repeatStreak, goal.lastReplyHash ?? null, goal.blockedStreak, goal.blockedRun ?? null, goal.continuations, goal.inflight ?? null, goal.lastRunId ?? null, goal.kickoffSent ? 1 : 0, goal.ownerPid ?? null, goal.createdAt, goal.updatedAt, goal.completedAt ?? null);
94
+ }
95
+ /**
96
+ * Replaces (or creates) the goal of a session. `build` gets the previous goal, if any, so the
97
+ * new one can continue its epoch (a stale client then conflicts instead of acting on the new
98
+ * goal), or answer `"exists"` to refuse. With `expect`, a goal that moved on is not replaced.
99
+ */
100
+ replace(sessionId, build, expect) {
101
+ return this.db.transaction(() => {
102
+ const previous = this.get(sessionId);
103
+ const stale = staleness(previous, expect);
104
+ if (stale)
105
+ return stale;
106
+ const next = build(previous);
107
+ if (next === "exists")
108
+ return {
109
+ ok: false,
110
+ code: "exists",
111
+ message: "This session already has a goal. Confirm to replace it.",
112
+ };
113
+ this.write(next);
114
+ return { ok: true, goal: next, value: previous };
115
+ });
116
+ }
117
+ /**
118
+ * Read-modify-write. `change` returns the new record (or undefined to leave it untouched) and
119
+ * a value for the caller; it must be pure (it may run inside a retried transaction).
120
+ */
121
+ update(sessionId, change, expect) {
122
+ return this.db.transaction(() => {
123
+ const current = this.get(sessionId);
124
+ if (!current)
125
+ return { ok: false, code: "not_found", message: "No goal." };
126
+ const stale = staleness(current, expect);
127
+ if (stale)
128
+ return stale;
129
+ const { goal, value } = change(current);
130
+ if (goal && goal !== current)
131
+ this.write(goal);
132
+ return { ok: true, goal: goal ?? current, value };
133
+ });
134
+ }
135
+ /** Removes the goal. With `expect`, only the goal the caller saw. */
136
+ delete(sessionId, expect) {
137
+ return this.db.transaction(() => {
138
+ const current = this.get(sessionId);
139
+ if (!current)
140
+ return { ok: false, code: "not_found", message: "No goal." };
141
+ const stale = staleness(current, expect);
142
+ if (stale)
143
+ return stale;
144
+ this.db.prepare("DELETE FROM session_goals WHERE session=?").run(sessionId);
145
+ return { ok: true, goal: current, value: undefined };
146
+ });
147
+ }
148
+ /**
149
+ * Startup recovery: an `active` goal whose driving process is gone (or unknown) pauses with
150
+ * reason `restart`. A goal driven by this very process (another application in it) or by a
151
+ * live one is left alone. Returns the goals that paused.
152
+ */
153
+ pauseOrphans(now, alive = isProcessAlive) {
154
+ return this.db.transaction(() => {
155
+ const paused = [];
156
+ for (const goal of this.active()) {
157
+ const owner = goal.ownerPid;
158
+ if (owner && (owner === process.pid || alive(owner)))
159
+ continue;
160
+ const next = systemRestart(goal, now);
161
+ this.write(next);
162
+ paused.push(next);
163
+ }
164
+ return paused;
165
+ });
166
+ }
167
+ /** Sessions that have a goal in the given statuses (for lists). */
168
+ sessionsWith(status) {
169
+ return this.db.prepare("SELECT session FROM session_goals WHERE status=?").all(status).map((row) => row.session);
170
+ }
171
+ }
172
+ function staleness(current, expect) {
173
+ if (!expect || !current)
174
+ return undefined;
175
+ if (expect.goalId !== undefined && expect.goalId !== current.goalId)
176
+ return { ok: false, code: "conflict", message: "The goal was replaced by another one." };
177
+ if (expect.epoch !== undefined && expect.epoch !== current.epoch)
178
+ return {
179
+ ok: false,
180
+ code: "conflict",
181
+ message: "The goal changed since you last saw it (another window or the agent updated it).",
182
+ };
183
+ return undefined;
184
+ }
package/dist/index.d.ts CHANGED
@@ -1,29 +1,74 @@
1
1
  /** @alisio/core public API: embed the Alisio agent programmatically. */
2
2
  export * from "@alisio/sdk";
3
+ export { type ActiveAgent, AGENT_COMMAND_PREFIX, type AgentPickerItem, activeAgentCatalog, agentCatalogFromState, agentCommandDescriptors, agentCommandName, agentIdFromCommand, agentPickerItems, agentRunOptions, BUILTIN_AGENTS, cycleableAgents, DEFAULT_AGENT_ID, type MainCapableAgentRecord, mainAgentFromRecord, nextAgent, PLAN_AGENT_ID, resolveActiveAgent, } from "./agents/active.ts";
4
+ export { agentModelCapabilities, agentModelLabels, agentModelOptions, DEFAULT_EFFORT_LEVELS, fitAgentSettings, } from "./agents/capabilities.ts";
5
+ export { AGENT_AUTHORING_SKILL_NAMES, CREATE_AGENT_SKILL, } from "./agents/create-agent-skill.ts";
6
+ export { AGENT_ID_PATTERN, AGENT_LIMITS, AGENT_REASONING_SUMMARIES, AGENT_TEXT_FORMATS, AGENT_VERBOSITIES, type AgentFieldError, AgentNotFoundError, AgentScopeStore, agentIdFromName, agentScopeDir, parseAgentFile, RESERVED_AGENT_IDS, slugify, validateAgentDefinitionInput, } from "./agents/definitions.ts";
7
+ export { AGENT_DRAFT_INSTRUCTIONS, AGENT_DRAFT_MAX_DESCRIPTION, type AgentAuthoringGuidance, agentAuthoringGuidance, agentDraftRequest, generateAgentDraft, parseAgentDraft, } from "./agents/draft.ts";
8
+ export { type AgentChange, AgentDefinitionService, type AgentDefinitionServiceOptions, type AgentRegistry, mergeAgentScopes, } from "./agents/service.ts";
9
+ export { AGENT_TEMPLATES, agentTemplate } from "./agents/templates.ts";
10
+ export { CapabilityGrants, type GrantRecord, type GrantSource, toGrantWire, } from "./analysis/capabilities.ts";
11
+ export { CsvParser, decodeTextBytes, detectDelimiter } from "./analysis/data/csv.ts";
12
+ export { type DatasetLimits, type DatasetRecord, DatasetService, DEFAULT_DATASET_LIMITS, datasetFormat, PageParamError, toDatasetRef, XLSX_REMEDY, } from "./analysis/data/datasets.ts";
13
+ export { DataEngine, DataError, type DataErrorCode, } from "./analysis/data/engine-client.ts";
14
+ export { guardSql } from "./analysis/data/sql-guard.ts";
15
+ export { detectHintHost, type HintHost, type InstallHints, installHintsMarkdown, installHintsText, parseOsRelease, pythonInstallHints, } from "./analysis/install-hints.ts";
16
+ export { AnalysisJanitor, type RetentionPolicy, SWEEP_INTERVAL_MS, type SweepReport, } from "./analysis/janitor.ts";
17
+ export { AnalysisJobs, type ExecutionDetails, type ExecutionStatus, type JobPaths, } from "./analysis/jobs.ts";
18
+ export { containerName, type OciDeps, type OciEngine, OciRuntime, type OciSettings, type OciStatus, ociRunArgs, parseDigests, } from "./analysis/oci.ts";
19
+ export { AnalysisRerun, type RerunPlan, type RerunPreparation, } from "./analysis/rerun.ts";
20
+ export { AnalysisRuntimeManager, type DiscoveryDeps, type Extras, ExtrasInstallError, type InstallStep, installPreview, type PythonCandidate, type PythonResolution, type RuntimeState, setupCommand, venvInterpreter, } from "./analysis/runtime-manager.ts";
21
+ export { analysisStatus } from "./analysis/status.ts";
3
22
  export { type AppOptions, type BuiltinContext, type BuiltinPlugin, createApplication, enabledBuiltins, type PluginCatalogEntry, type PluginCatalogStatus, } from "./application.ts";
4
- export { type Config, type ConfigLoadResult, type ConfigProvenance, configFile, configHome, configSchema, isSettableSettingKey, type LoadedConfig, loadConfig, loadConfigWithProvenance, type McpServerSource, overridesSavedProviderProfile, type SettableSettingKey, setConfigValue, setGlobalMcpAllow, setMcpServerEnabled, setProjectPluginEnabled, setProjectSkillEnabled, stateHome, } from "./config.ts";
23
+ export { classifyArtifact, extensionOf, fileType as artifactFileType, isPreviewable, KIND_LABELS, viewerContentType, } from "./artifacts/kinds.ts";
24
+ export { createArtifactPublisher } from "./artifacts/publisher.ts";
25
+ export { type ArtifactFile, type ArtifactLimits, type ArtifactOwner, type ArtifactRecord, ArtifactRejected, ArtifactStore, type PublishedArtifact, readHead as readArtifactHead, slugify as artifactSlug, toRef, } from "./artifacts/store.ts";
26
+ export { TaskJanitor } from "./background/janitor.ts";
27
+ export { subagentTasks } from "./background/mirror.ts";
28
+ export { buildTaskNotification, DEFAULT_NOTIFIER_TIMING, type NotifierTiming, TaskNotifier, type TaskWake, type TaskWakeRequest, type WakeOutcome, } from "./background/notify.ts";
29
+ export { DEFAULT_READ_BYTES, MAX_READ_BYTES } from "./background/output.ts";
30
+ export { BackgroundTasks, type BackgroundTasksOptions, type TaskAdmissionCode, TaskAdmissionError, TaskForeignError, TaskNotFoundError, } from "./background/service.ts";
31
+ export { BackgroundTaskStore, isLive as isTaskLive, isTerminal as isTaskTerminal, } from "./background/store.ts";
32
+ export { changelogNews, compareVersions, formatChangelogMarkdown, isVersion, loadChangelog, type NewsDecision, parseChangelog, type SelectedEntries, selectEntries, UNRELEASED, } from "./changelog/index.ts";
33
+ export { BUILTIN_COMMANDS, type BuiltinCommand, CommandCatalog, type CommandExecutionContext, type CommandHost, type CommandResult, type CommandSurface, } from "./commands/catalog.ts";
34
+ export { type Config, type ConfigLoadResult, type ConfigProvenance, configFile, configHome, configSchema, isSettableSettingKey, type LoadedConfig, loadConfig, loadConfigWithProvenance, type McpServerSource, OCI_IMAGE_PATTERN, overridesSavedProviderProfile, type SettableSettingInfo, type SettableSettingKey, setConfigValue, setGlobalMcpAllow, setMcpServerEnabled, setProjectPluginEnabled, setProjectSkillEnabled, settableSettings, stateHome, } from "./config.ts";
5
35
  export { type ContextBudget, checkpointInstructions, completeText, effectiveContextBudget, estimateTokens, MAX_TRUSTED_WINDOW, parseCheckpointOutput, planCompaction, renderCheckpoint, serializeForSummary, shouldCompact, shouldCompactContext, summarize, } from "./core/compaction.ts";
6
- export type { ApprovalDecision, ApprovalHandler, ApprovalRequest, ContextSource, HookFailure, Policy, RunnerExtensions, Session, SessionStore, } from "./core/contracts.ts";
36
+ export type { ApprovalDecision, ApprovalHandler, ApprovalRequest, ArtifactPublisherFactory, BeginRunInput, CapabilityGate, ContextSource, CoreArtifactPublisher, EndRunInput, EventPage, HookFailure, MessagePage, PageOptions, Policy, PublishedArtifactInfo, RunnerExtensions, RunRecord, RunStatus, Session, SessionStore, StoredEvent, TerminalRunStatus, ToolCallMeta, } from "./core/contracts.ts";
37
+ export { EXIT_PLAN_TOOL, GOAL_TOOLS, OPT_IN_TOOLS } from "./core/opt-in.ts";
38
+ export { DEFAULT_MAX_OUTPUT_TOKENS, describeOutputLimitSource, MAX_AUTO_OUTPUT_TOKENS, type OutputLimit, type OutputLimitSource, resolveMaxOutputTokens, } from "./core/output-limit.ts";
7
39
  export { ToolRegistry } from "./core/registry.ts";
8
40
  export { AgentRunner, type CompactionResult, defaultTokenBudget, type RunnerOptions, type RunnerSettingsPatch, type RunOptions, } from "./core/runner.ts";
9
41
  export { type ExtensionConflict, ExtensionRegistry } from "./extensions/registry.ts";
42
+ export * from "./goal/index.ts";
10
43
  export { HerdrBridge } from "./integrations/herdr.ts";
11
44
  export { McpConnector, type McpServerInfo, type McpStatus, type McpToolInfo, } from "./mcp/connector.ts";
12
- export { discoverPlugins, PluginHost, type PluginHostOptions, pluginPrefix, } from "./plugins/host.ts";
45
+ export { describePermissionStatus, type EffectState, effectState, FULL_ACCESS_WARNING, type ModeFlags, type ModePolicy, modeFromFlags, modeToPreset, PERMISSION_MODE_TABLE, PERMISSION_MODES, PERMISSION_MODES_LOCKED, PERMISSION_USAGE, type PermissionCommand, type PermissionModeLabel, type PermissionModeSpec, parsePermissionCommand, parsePermissionMode, presetToMode, READ_ONLY_POLICY, } from "./permissions/modes.ts";
46
+ export { claimApprovedPlan, currentPlan, discardApprovedPlan, IMPLEMENTATION_AGENT_ID, implementationPrompt, PLAN_CONTEXT_MAX_CHARS, PLAN_OPTIONS, PLAN_QUESTION_ID, PLAN_REVIEW_TITLE, PLAN_TEXT_KEY, type PlanFollowUp, type PlanState, type PlanStatus, planHash, readPlanState, settlePlanRun, withdrawPendingPlan, } from "./plan/state.ts";
47
+ export { discoverPlugins, PluginHost, type PluginHostOptions, pluginPrefix, type ViewInfo, ViewRunError, } from "./plugins/host.ts";
13
48
  export { type CliInstallOptions, cliInstall, INSTALL_TIMEOUT_MS, type InstallPluginInput, type InstallPluginResult, type InstallRunner, installedNpmPlugins, installPlugin, npmInstallTarget, type PluginSpec, parsePluginSpec, pluginTrustRemark, printInstallResult, registerPluginInstallTool, sanitizeNpmError, } from "./plugins/install.ts";
14
49
  export { ActiveProvider, ProviderRegistry, UnconfiguredProvider } from "./providers/registry.ts";
15
50
  export { availableProviderModels, type ProviderModelCatalog, resolveProviderModel, } from "./providers/routing.ts";
16
- export { type ProviderProfile, type ProviderSettings, ProviderSettingsStore, } from "./providers/settings.ts";
51
+ export { maskSecret, type ProviderProfile, type ProviderSettings, ProviderSettingsStore, } from "./providers/settings.ts";
52
+ export { buildReloadReport, formatReloadReport, type ReloadableApp, ReloadFailedError, type ReloadInput, ReloadRefusedError, type ReloadSnapshot, reloadApplication, snapshotApplication, validateReloadConfig, } from "./reload.ts";
17
53
  export { type InstructionFile, ProjectContext, type ProjectContextOptions, } from "./resources/context.ts";
18
54
  export { expandSlashPrompt, loadPromptTemplates, type PromptDiagnostic, type PromptRequirement, type PromptSource, type PromptSourceKind, type PromptTemplate, parsePromptTemplate, promptSources, renderPromptTemplate, splitArguments, } from "./resources/prompts.ts";
19
55
  export { type Skill, type SkillCatalogEntry, type SkillRoot, type SkillScope, Skills, skillRoots, } from "./resources/skills.ts";
56
+ export { type ExternalDirectoryDecision, type ExternalDirectoryHandler, type ExternalDirectoryRequest, PathAccess, type PathAccessOptions, type ResolvePathOptions, } from "./runtime/access.ts";
57
+ export { BlobStore, type BlobStoreOptions, BlobTooLarge } from "./runtime/blobs.ts";
58
+ export { clipLines, unifiedPatch } from "./runtime/diff.ts";
20
59
  export { exists, fileSize, readHead, readJson, readText, which } from "./runtime/fs.ts";
60
+ export { newId, ulid } from "./runtime/ids.ts";
21
61
  export { defaultGlobalRoots, isPathSpec, PLUGIN_KEYWORD, resolvePluginSpec, } from "./runtime/modules.ts";
22
- export { findWorkspace, safePath } from "./runtime/paths.ts";
62
+ export { findWorkspace, inside, outsideRootsMessage, safePath, workspaceKey, } from "./runtime/paths.ts";
23
63
  export { isMissingCommand, type ProcessResult, RIPGREP_INSTALL_HINT, runProcess, } from "./runtime/process.ts";
24
64
  export { isSqliteExperimentalWarning, openDatabase } from "./runtime/sqlite.ts";
25
65
  export { SQLiteStore } from "./runtime/store.ts";
66
+ export { crc32, writeZip, type ZipEntry, type ZipSink } from "./runtime/zip.ts";
26
67
  export { ChildSessions, type ChildSessionsOptions } from "./sessions/children.ts";
68
+ export { formatSideQuestion, SIDE_QUESTION_DESCRIPTION, SIDE_QUESTION_HISTORY_LIMIT, SIDE_QUESTION_INSTRUCTIONS, SIDE_QUESTION_MAX_CHARS, SIDE_QUESTION_USAGE, SIDE_QUESTIONS_NAMESPACE, type SideQuestionEntry, SideQuestions, type SideQuestionsOptions, sideTranscript, } from "./sessions/side-questions.ts";
27
69
  export { composeSideBySide, DefaultAlisioMascot, DefaultStartupScreen, infoSection, mascotSection, padEnd, pluginsSection, renderStartup, type StartupDiagnostic, type StartupInput, type StartupResult, sanitizeLine, shortenPath, startupTips, stripAnsi, tipsSection, titleSection, truncate, visibleWidth, welcomeSection, } from "./startup/index.ts";
70
+ export { formatBytes, NOT_SANDBOXED } from "./tools/analysis.ts";
71
+ export { ARTIFACT_READ_MAX, exportedPaths } from "./tools/artifacts.ts";
72
+ export { GET_GOAL_TOOL, parseEvidence, UPDATE_GOAL_TOOL } from "./tools/goal.ts";
28
73
  export { hash, objectSchema, registerStandard } from "./tools/standard.ts";
29
74
  export { getTrust, hashProjectConfig, hasProjectResources, listTrust, resolveTrust, revokeTrust, setTrust, type TrustEntry, type TrustListing, type TrustResolution, trustStorePath, } from "./trust.ts";
package/dist/index.js CHANGED
@@ -1,28 +1,73 @@
1
1
  /** @alisio/core public API: embed the Alisio agent programmatically. */
2
2
  export * from "@alisio/sdk";
3
+ export { AGENT_COMMAND_PREFIX, activeAgentCatalog, agentCatalogFromState, agentCommandDescriptors, agentCommandName, agentIdFromCommand, agentPickerItems, agentRunOptions, BUILTIN_AGENTS, cycleableAgents, DEFAULT_AGENT_ID, mainAgentFromRecord, nextAgent, PLAN_AGENT_ID, resolveActiveAgent, } from "./agents/active.js";
4
+ export { agentModelCapabilities, agentModelLabels, agentModelOptions, DEFAULT_EFFORT_LEVELS, fitAgentSettings, } from "./agents/capabilities.js";
5
+ export { AGENT_AUTHORING_SKILL_NAMES, CREATE_AGENT_SKILL, } from "./agents/create-agent-skill.js";
6
+ export { AGENT_ID_PATTERN, AGENT_LIMITS, AGENT_REASONING_SUMMARIES, AGENT_TEXT_FORMATS, AGENT_VERBOSITIES, AgentNotFoundError, AgentScopeStore, agentIdFromName, agentScopeDir, parseAgentFile, RESERVED_AGENT_IDS, slugify, validateAgentDefinitionInput, } from "./agents/definitions.js";
7
+ export { AGENT_DRAFT_INSTRUCTIONS, AGENT_DRAFT_MAX_DESCRIPTION, agentAuthoringGuidance, agentDraftRequest, generateAgentDraft, parseAgentDraft, } from "./agents/draft.js";
8
+ export { AgentDefinitionService, mergeAgentScopes, } from "./agents/service.js";
9
+ export { AGENT_TEMPLATES, agentTemplate } from "./agents/templates.js";
10
+ export { CapabilityGrants, toGrantWire, } from "./analysis/capabilities.js";
11
+ export { CsvParser, decodeTextBytes, detectDelimiter } from "./analysis/data/csv.js";
12
+ export { DatasetService, DEFAULT_DATASET_LIMITS, datasetFormat, PageParamError, toDatasetRef, XLSX_REMEDY, } from "./analysis/data/datasets.js";
13
+ export { DataEngine, DataError, } from "./analysis/data/engine-client.js";
14
+ export { guardSql } from "./analysis/data/sql-guard.js";
15
+ export { detectHintHost, installHintsMarkdown, installHintsText, parseOsRelease, pythonInstallHints, } from "./analysis/install-hints.js";
16
+ export { AnalysisJanitor, SWEEP_INTERVAL_MS, } from "./analysis/janitor.js";
17
+ export { AnalysisJobs, } from "./analysis/jobs.js";
18
+ export { containerName, OciRuntime, ociRunArgs, parseDigests, } from "./analysis/oci.js";
19
+ export { AnalysisRerun, } from "./analysis/rerun.js";
20
+ export { AnalysisRuntimeManager, ExtrasInstallError, installPreview, setupCommand, venvInterpreter, } from "./analysis/runtime-manager.js";
21
+ export { analysisStatus } from "./analysis/status.js";
3
22
  export { createApplication, enabledBuiltins, } from "./application.js";
4
- export { configFile, configHome, configSchema, isSettableSettingKey, loadConfig, loadConfigWithProvenance, overridesSavedProviderProfile, setConfigValue, setGlobalMcpAllow, setMcpServerEnabled, setProjectPluginEnabled, setProjectSkillEnabled, stateHome, } from "./config.js";
23
+ export { classifyArtifact, extensionOf, fileType as artifactFileType, isPreviewable, KIND_LABELS, viewerContentType, } from "./artifacts/kinds.js";
24
+ export { createArtifactPublisher } from "./artifacts/publisher.js";
25
+ export { ArtifactRejected, ArtifactStore, readHead as readArtifactHead, slugify as artifactSlug, toRef, } from "./artifacts/store.js";
26
+ export { TaskJanitor } from "./background/janitor.js";
27
+ export { subagentTasks } from "./background/mirror.js";
28
+ export { buildTaskNotification, DEFAULT_NOTIFIER_TIMING, TaskNotifier, } from "./background/notify.js";
29
+ export { DEFAULT_READ_BYTES, MAX_READ_BYTES } from "./background/output.js";
30
+ export { BackgroundTasks, TaskAdmissionError, TaskForeignError, TaskNotFoundError, } from "./background/service.js";
31
+ export { BackgroundTaskStore, isLive as isTaskLive, isTerminal as isTaskTerminal, } from "./background/store.js";
32
+ export { changelogNews, compareVersions, formatChangelogMarkdown, isVersion, loadChangelog, parseChangelog, selectEntries, UNRELEASED, } from "./changelog/index.js";
33
+ export { BUILTIN_COMMANDS, CommandCatalog, } from "./commands/catalog.js";
34
+ export { configFile, configHome, configSchema, isSettableSettingKey, loadConfig, loadConfigWithProvenance, OCI_IMAGE_PATTERN, overridesSavedProviderProfile, setConfigValue, setGlobalMcpAllow, setMcpServerEnabled, setProjectPluginEnabled, setProjectSkillEnabled, settableSettings, stateHome, } from "./config.js";
5
35
  export { checkpointInstructions, completeText, effectiveContextBudget, estimateTokens, MAX_TRUSTED_WINDOW, parseCheckpointOutput, planCompaction, renderCheckpoint, serializeForSummary, shouldCompact, shouldCompactContext, summarize, } from "./core/compaction.js";
36
+ export { EXIT_PLAN_TOOL, GOAL_TOOLS, OPT_IN_TOOLS } from "./core/opt-in.js";
37
+ export { DEFAULT_MAX_OUTPUT_TOKENS, describeOutputLimitSource, MAX_AUTO_OUTPUT_TOKENS, resolveMaxOutputTokens, } from "./core/output-limit.js";
6
38
  export { ToolRegistry } from "./core/registry.js";
7
39
  export { AgentRunner, defaultTokenBudget, } from "./core/runner.js";
8
40
  export { ExtensionRegistry } from "./extensions/registry.js";
41
+ export * from "./goal/index.js";
9
42
  export { HerdrBridge } from "./integrations/herdr.js";
10
43
  export { McpConnector, } from "./mcp/connector.js";
11
- export { discoverPlugins, PluginHost, pluginPrefix, } from "./plugins/host.js";
44
+ export { describePermissionStatus, effectState, FULL_ACCESS_WARNING, modeFromFlags, modeToPreset, PERMISSION_MODE_TABLE, PERMISSION_MODES, PERMISSION_MODES_LOCKED, PERMISSION_USAGE, parsePermissionCommand, parsePermissionMode, presetToMode, READ_ONLY_POLICY, } from "./permissions/modes.js";
45
+ export { claimApprovedPlan, currentPlan, discardApprovedPlan, IMPLEMENTATION_AGENT_ID, implementationPrompt, PLAN_CONTEXT_MAX_CHARS, PLAN_OPTIONS, PLAN_QUESTION_ID, PLAN_REVIEW_TITLE, PLAN_TEXT_KEY, planHash, readPlanState, settlePlanRun, withdrawPendingPlan, } from "./plan/state.js";
46
+ export { discoverPlugins, PluginHost, pluginPrefix, ViewRunError, } from "./plugins/host.js";
12
47
  export { cliInstall, INSTALL_TIMEOUT_MS, installedNpmPlugins, installPlugin, npmInstallTarget, parsePluginSpec, pluginTrustRemark, printInstallResult, registerPluginInstallTool, sanitizeNpmError, } from "./plugins/install.js";
13
48
  export { ActiveProvider, ProviderRegistry, UnconfiguredProvider } from "./providers/registry.js";
14
49
  export { availableProviderModels, resolveProviderModel, } from "./providers/routing.js";
15
- export { ProviderSettingsStore, } from "./providers/settings.js";
50
+ export { maskSecret, ProviderSettingsStore, } from "./providers/settings.js";
51
+ export { buildReloadReport, formatReloadReport, ReloadFailedError, ReloadRefusedError, reloadApplication, snapshotApplication, validateReloadConfig, } from "./reload.js";
16
52
  export { ProjectContext, } from "./resources/context.js";
17
53
  export { expandSlashPrompt, loadPromptTemplates, parsePromptTemplate, promptSources, renderPromptTemplate, splitArguments, } from "./resources/prompts.js";
18
54
  export { Skills, skillRoots, } from "./resources/skills.js";
55
+ export { PathAccess, } from "./runtime/access.js";
56
+ export { BlobStore, BlobTooLarge } from "./runtime/blobs.js";
57
+ export { clipLines, unifiedPatch } from "./runtime/diff.js";
19
58
  export { exists, fileSize, readHead, readJson, readText, which } from "./runtime/fs.js";
59
+ export { newId, ulid } from "./runtime/ids.js";
20
60
  export { defaultGlobalRoots, isPathSpec, PLUGIN_KEYWORD, resolvePluginSpec, } from "./runtime/modules.js";
21
- export { findWorkspace, safePath } from "./runtime/paths.js";
61
+ export { findWorkspace, inside, outsideRootsMessage, safePath, workspaceKey, } from "./runtime/paths.js";
22
62
  export { isMissingCommand, RIPGREP_INSTALL_HINT, runProcess, } from "./runtime/process.js";
23
63
  export { isSqliteExperimentalWarning, openDatabase } from "./runtime/sqlite.js";
24
64
  export { SQLiteStore } from "./runtime/store.js";
65
+ export { crc32, writeZip } from "./runtime/zip.js";
25
66
  export { ChildSessions } from "./sessions/children.js";
67
+ export { formatSideQuestion, SIDE_QUESTION_DESCRIPTION, SIDE_QUESTION_HISTORY_LIMIT, SIDE_QUESTION_INSTRUCTIONS, SIDE_QUESTION_MAX_CHARS, SIDE_QUESTION_USAGE, SIDE_QUESTIONS_NAMESPACE, SideQuestions, sideTranscript, } from "./sessions/side-questions.js";
26
68
  export { composeSideBySide, DefaultAlisioMascot, DefaultStartupScreen, infoSection, mascotSection, padEnd, pluginsSection, renderStartup, sanitizeLine, shortenPath, startupTips, stripAnsi, tipsSection, titleSection, truncate, visibleWidth, welcomeSection, } from "./startup/index.js";
69
+ export { formatBytes, NOT_SANDBOXED } from "./tools/analysis.js";
70
+ export { ARTIFACT_READ_MAX, exportedPaths } from "./tools/artifacts.js";
71
+ export { GET_GOAL_TOOL, parseEvidence, UPDATE_GOAL_TOOL } from "./tools/goal.js";
27
72
  export { hash, objectSchema, registerStandard } from "./tools/standard.js";
28
73
  export { getTrust, hashProjectConfig, hasProjectResources, listTrust, resolveTrust, revokeTrust, setTrust, trustStorePath, } from "./trust.js";
@@ -4,7 +4,18 @@ import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/cli
4
4
  import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
5
5
  import { objectSchema } from "../tools/standard.js";
6
6
  import { loadVersion } from "../version.js";
7
+ import { mapMcpCallResult, mapMcpResourceResult } from "./rich.js";
7
8
  const TOOL_NAME_LIMIT = 64;
9
+ /**
10
+ * Per-server client close cap used ONLY by the terminal `close()`: the MCP SDK's stdio close can
11
+ * take ~4s worst case (stdin end → 2s → SIGTERM → 2s → SIGKILL) when a server ignores
12
+ * termination, and exit must never wait for that ladder. Runtime `disconnect()` keeps its
13
+ * unbounded semantics so interactive reconnect flows stay unchanged.
14
+ */
15
+ const CLOSE_SERVER_TIMEOUT_MS = 800;
16
+ /** Overall cap for `close()` (every connected server in parallel plus bridge unregistration). */
17
+ const CLOSE_TOTAL_TIMEOUT_MS = 1_500;
18
+ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
8
19
  const semanticSegment = (value, fallback) => value
9
20
  .normalize("NFKD")
10
21
  .replace(/[\u0300-\u036f]/g, "")
@@ -101,7 +112,7 @@ export class McpConnector {
101
112
  const result = i.uri
102
113
  ? await client.readResource({ uri: String(i.uri) }, { signal: c.signal, timeout: 15000 })
103
114
  : await client.listResources(undefined, { signal: c.signal, timeout: 15000 });
104
- return textResult(JSON.stringify(result));
115
+ return mapMcpResourceResult(result);
105
116
  },
106
117
  }));
107
118
  undo.push(this.registry.register({
@@ -208,7 +219,7 @@ export class McpConnector {
208
219
  if (!config)
209
220
  throw new Error(`Unknown MCP server: ${name}`);
210
221
  if (!config.enabled)
211
- throw new Error(`MCP server "${name}" is disabled; enable it in /mcp`);
222
+ throw new Error(`MCP server "${name}" is disabled; enable it in /mcps`);
212
223
  if (this.clients.has(name))
213
224
  return this.registeredNames(name);
214
225
  if (config.transport === "http" &&
@@ -319,7 +330,7 @@ export class McpConnector {
319
330
  JSON.stringify(current.inputSchema) !== JSON.stringify(tool.inputSchema))
320
331
  throw new Error("MCP schema changed; reconnect the server to refresh tools");
321
332
  const result = await client.callTool({ name: tool.name, arguments: input }, { signal: ctx.signal, timeout: 30000 });
322
- return textResult(JSON.stringify(result), "isError" in result && result.isError === true);
333
+ return mapMcpCallResult(result);
323
334
  },
324
335
  }));
325
336
  }
@@ -385,8 +396,29 @@ export class McpConnector {
385
396
  return [...(this.clients.get(name)?.registeredNames ?? [])];
386
397
  }
387
398
  async close() {
388
- await Promise.all([...this.clients.keys()].map((name) => this.disconnect(name)));
389
- for (const undo of this.bridgeUndo.splice(0).reverse())
390
- undo();
399
+ const servers = [...this.clients.keys()];
400
+ // Exit latency is user-facing: every server is disconnected in parallel, each client close
401
+ // raced against a short cap, and the whole phase against an overall cap. An abandoned close
402
+ // keeps running in the background and the SDK still SIGKILLs an unresponsive server; the
403
+ // registry cleanup runs synchronously inside `disconnect`, so tools are always unregistered.
404
+ await Promise.race([
405
+ (async () => {
406
+ await Promise.all(servers.map((name) => Promise.race([this.disconnect(name), delay(CLOSE_SERVER_TIMEOUT_MS)])));
407
+ for (const undo of this.bridgeUndo.splice(0).reverse())
408
+ undo();
409
+ })(),
410
+ delay(CLOSE_TOTAL_TIMEOUT_MS),
411
+ ]);
412
+ // A raced `disconnect` may have been abandoned before its final status cleanup (it flips
413
+ // the status only after `client.close()` resolves): the client entry is already gone, so
414
+ // settle the status here for exit without touching runtime disconnect semantics.
415
+ for (const name of servers) {
416
+ if (this.clients.has(name) || this.statuses.get(name) !== "connected")
417
+ continue;
418
+ const server = this.servers[name];
419
+ if (!server)
420
+ continue;
421
+ this.statuses.set(name, server.enabled ? "disconnected" : "disabled");
422
+ }
391
423
  }
392
424
  }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * MCP → Alisio result mapping ("Nivel 0" rich tool results).
3
+ *
4
+ * MCP protocol types never leak into the SDK: this adapter is the single place that folds an
5
+ * MCP `CallToolResult` / `ReadResourceResult` into the Alisio-owned `ToolResult` content union
6
+ * (text, image, ui blocks). Mapping is heuristic and conservative:
7
+ *
8
+ * - `text` parts stay text parts; an image part becomes `{type:"image"}` (base64 data + mime).
9
+ * - `structuredContent` (or a JSON-parseable text part) is folded into a `ui` block when it
10
+ * matches a verified shape — `{columns,rows}` / `{headers,rows}` tables, all-scalar
11
+ * key-value objects, or `{nodes:[{label,children,meta}]}` trees. Anything else stays text
12
+ * (the previous flattening).
13
+ * - A canonical text projection of every ui block / image is ALWAYS appended as a text part so
14
+ * providers, compaction and headless output only see text.
15
+ * - Unknown call results (no contents, nothing recognized) keep the previous
16
+ * `JSON.stringify(result)` behavior verbatim.
17
+ */
18
+ import { type ToolResult, type UiBlock } from "@alisio/sdk";
19
+ /**
20
+ * Folds a candidate value into a UiBlock when it matches one of the verified shapes:
21
+ * `{columns,rows}` / `{headers,rows}` tables, `{nodes:[...]}` trees, or flat scalar objects.
22
+ */
23
+ export declare function blockFromUnknown(value: unknown): UiBlock | undefined;
24
+ /** Tries a JSON-parseable text part: recognized shapes become ui blocks, everything else stays text. */
25
+ export declare function blockFromJsonText(text: string): UiBlock | undefined;
26
+ /** Compact plain-text rendering of a ui block, used as the canonical model-visible projection. */
27
+ export declare function renderUiBlockText(block: UiBlock): string;
28
+ /**
29
+ * Maps an MCP `CallToolResult` into an Alisio `ToolResult`. Text/image parts map directly;
30
+ * verified table/key-value/tree shapes (from `structuredContent` or JSON text parts) become
31
+ * `ui` blocks; a canonical text projection is always appended when non-text parts exist, and
32
+ * unrecognized results keep the previous `JSON.stringify` flattening verbatim.
33
+ */
34
+ export declare function mapMcpCallResult(result: unknown): ToolResult;
35
+ /**
36
+ * Maps an MCP `ReadResourceResult` / `ListResourcesResult` into an Alisio `ToolResult`.
37
+ * Text contents map to text parts; image blobs become `{type:"image"}` parts; non-image blobs
38
+ * become a text marker (never raw base64 in the model prompt). Results without contents (a
39
+ * resource listing, for example) keep the previous `JSON.stringify` flattening.
40
+ */
41
+ export declare function mapMcpResourceResult(result: unknown): ToolResult;