@acryldev/harness-runtime 0.0.0-stage → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/LICENSE +49 -0
  2. package/lib/index.mjs +5693 -0
  3. package/lib/index.mjs.map +1 -0
  4. package/lib/types/acryl-home.d.ts +81 -0
  5. package/lib/types/app/new-app.d.ts +65 -0
  6. package/lib/types/app/start-source.d.ts +47 -0
  7. package/lib/types/blueprint/blueprint.d.ts +74 -0
  8. package/lib/types/blueprint/brand-identity.d.ts +26 -0
  9. package/lib/types/blueprint/compose.d.ts +53 -0
  10. package/lib/types/blueprint/definition.d.ts +22 -0
  11. package/lib/types/blueprint/index.d.ts +7 -0
  12. package/lib/types/blueprint/manifest.d.ts +35 -0
  13. package/lib/types/blueprint/selection.d.ts +19 -0
  14. package/lib/types/cli-market-install.d.ts +97 -0
  15. package/lib/types/cli-market-plugins.d.ts +81 -0
  16. package/lib/types/coding-capabilities.d.ts +29 -0
  17. package/lib/types/durable-message.d.ts +18 -0
  18. package/lib/types/engine-dsh.d.ts +181 -0
  19. package/lib/types/engine-files.d.ts +8 -0
  20. package/lib/types/engine-host.d.ts +32 -0
  21. package/lib/types/engine-tools.d.ts +11 -0
  22. package/lib/types/index.d.ts +67 -0
  23. package/lib/types/instance/announce-self.d.ts +38 -0
  24. package/lib/types/instance/app-instance.d.ts +125 -0
  25. package/lib/types/instance/index.d.ts +6 -0
  26. package/lib/types/instance/offline-lock.d.ts +29 -0
  27. package/lib/types/instance/online-secret.d.ts +29 -0
  28. package/lib/types/instance/registry.d.ts +26 -0
  29. package/lib/types/instance/select.d.ts +43 -0
  30. package/lib/types/module-hooks.d.ts +19 -0
  31. package/lib/types/module-resolution.d.ts +31 -0
  32. package/lib/types/package-overlay.d.ts +41 -0
  33. package/lib/types/pinned-pnpm.d.ts +15 -0
  34. package/lib/types/plugin-acryl-workspace-status.d.ts +24 -0
  35. package/lib/types/plugin-doctor.d.ts +49 -0
  36. package/lib/types/plugin-lifecycle-state.d.ts +92 -0
  37. package/lib/types/plugin-lifecycle.d.ts +87 -0
  38. package/lib/types/profile-layout.d.ts +17 -0
  39. package/lib/types/profile-owner.d.ts +25 -0
  40. package/lib/types/profile-repair/backup.d.ts +37 -0
  41. package/lib/types/profile-repair/findings.d.ts +29 -0
  42. package/lib/types/profile-repair/index.d.ts +9 -0
  43. package/lib/types/profile-repair/inspector.d.ts +11 -0
  44. package/lib/types/profile-repair/repair.d.ts +38 -0
  45. package/lib/types/profile-resolution/moved-framework.d.ts +21 -0
  46. package/lib/types/profile-resolution/resolver.d.ts +41 -0
  47. package/lib/types/profile-resolution/service.d.ts +22 -0
  48. package/lib/types/prompt-budget.d.ts +44 -0
  49. package/lib/types/session-bridge.d.ts +57 -0
  50. package/lib/types/session-log-exporter.d.ts +31 -0
  51. package/lib/types/system-prompt-capture.d.ts +29 -0
  52. package/lib/types/web-favicon-data.d.ts +5 -0
  53. package/lib/types/web-favicon.d.ts +23 -0
  54. package/lib/types/web-market-install.d.ts +114 -0
  55. package/lib/types/web-market-plugins.d.ts +106 -0
  56. package/lib/types/web-port.d.ts +15 -0
  57. package/package.json +211 -3
  58. package/src/acryl-home.ts +103 -0
  59. package/src/app/new-app.ts +239 -0
  60. package/src/app/start-source.ts +110 -0
  61. package/src/blueprint/blueprint.ts +141 -0
  62. package/src/blueprint/brand-identity.ts +75 -0
  63. package/src/blueprint/compose.ts +222 -0
  64. package/src/blueprint/definition.ts +92 -0
  65. package/src/blueprint/index.ts +20 -0
  66. package/src/blueprint/manifest.ts +145 -0
  67. package/src/blueprint/selection.ts +74 -0
  68. package/src/cli-market-install.ts +181 -0
  69. package/src/cli-market-plugins.ts +176 -0
  70. package/src/coding-capabilities.ts +61 -0
  71. package/src/durable-message.ts +23 -0
  72. package/src/engine-dsh.ts +856 -0
  73. package/src/engine-files.ts +9 -0
  74. package/src/engine-host.ts +128 -0
  75. package/src/engine-tools.ts +26 -0
  76. package/src/index.ts +436 -0
  77. package/src/instance/announce-self.ts +88 -0
  78. package/src/instance/app-instance.ts +240 -0
  79. package/src/instance/index.ts +45 -0
  80. package/src/instance/offline-lock.ts +71 -0
  81. package/src/instance/online-secret.ts +55 -0
  82. package/src/instance/registry.ts +53 -0
  83. package/src/instance/select.ts +134 -0
  84. package/src/module-hooks.ts +41 -0
  85. package/src/module-resolution.ts +187 -0
  86. package/src/package-overlay.ts +160 -0
  87. package/src/pinned-pnpm.ts +67 -0
  88. package/src/plugin-acryl-workspace-status.ts +99 -0
  89. package/src/plugin-doctor.ts +141 -0
  90. package/src/plugin-lifecycle-state.ts +347 -0
  91. package/src/plugin-lifecycle.ts +223 -0
  92. package/src/profile-layout.ts +97 -0
  93. package/src/profile-owner.ts +52 -0
  94. package/src/profile-repair/backup.ts +119 -0
  95. package/src/profile-repair/findings.ts +43 -0
  96. package/src/profile-repair/index.ts +10 -0
  97. package/src/profile-repair/inspector.ts +156 -0
  98. package/src/profile-repair/repair.ts +137 -0
  99. package/src/profile-resolution/moved-framework.ts +64 -0
  100. package/src/profile-resolution/resolver.ts +876 -0
  101. package/src/profile-resolution/service.ts +99 -0
  102. package/src/prompt-budget.ts +118 -0
  103. package/src/session-bridge.ts +350 -0
  104. package/src/session-log-exporter.ts +68 -0
  105. package/src/system-prompt-capture.ts +99 -0
  106. package/src/web-favicon-data.ts +6 -0
  107. package/src/web-favicon.ts +43 -0
  108. package/src/web-market-install.ts +206 -0
  109. package/src/web-market-plugins.ts +215 -0
  110. package/src/web-port.ts +39 -0
  111. package/tests/account-callback.spec.ts +173 -0
  112. package/tests/acryl-home.spec.ts +39 -0
  113. package/tests/agent-self-hosting.spec.ts +101 -0
  114. package/tests/announce-self.spec.ts +84 -0
  115. package/tests/app-lifecycle.spec.ts +99 -0
  116. package/tests/blank-blueprint.spec.ts +110 -0
  117. package/tests/blueprint-definition.spec.ts +128 -0
  118. package/tests/blueprint.spec.ts +138 -0
  119. package/tests/bulkhead.spec.ts +187 -0
  120. package/tests/coding-vocabulary.spec.ts +15 -0
  121. package/tests/dump-system-prompt.spec.ts +65 -0
  122. package/tests/e2e-real-model.spec.ts +71 -0
  123. package/tests/e2e-restart-real-model.spec.ts +77 -0
  124. package/tests/engine-dsh.spec.ts +340 -0
  125. package/tests/engine-host-mount-root-include.spec.ts +118 -0
  126. package/tests/engine-host.spec.ts +176 -0
  127. package/tests/engine-optional.spec.ts +81 -0
  128. package/tests/extension-examples.spec.ts +261 -0
  129. package/tests/hooks-thread-stack.ts +27 -0
  130. package/tests/instance-patches.spec.ts +25 -0
  131. package/tests/instance.spec.ts +235 -0
  132. package/tests/live/community-plugins.spec.ts +83 -0
  133. package/tests/module-hooks.spec.ts +35 -0
  134. package/tests/module-resolution.spec.ts +265 -0
  135. package/tests/moved-framework.spec.ts +61 -0
  136. package/tests/new-app.spec.ts +132 -0
  137. package/tests/organizer-growth.spec.ts +117 -0
  138. package/tests/pinned-pnpm.spec.ts +34 -0
  139. package/tests/plugin-acryl-workspace-status.spec.ts +63 -0
  140. package/tests/plugin-context.spec.ts +640 -0
  141. package/tests/plugin-doctor.spec.ts +183 -0
  142. package/tests/plugin-enablement-one-store.spec.ts +130 -0
  143. package/tests/plugin-lifecycle-state.spec.ts +169 -0
  144. package/tests/profile-layout.spec.ts +58 -0
  145. package/tests/profile-owner.spec.ts +38 -0
  146. package/tests/profile-repair/profile-repair.spec.ts +231 -0
  147. package/tests/profile-resolution-port.spec.ts +30 -0
  148. package/tests/profile-resolution-service.spec.ts +273 -0
  149. package/tests/profile-resolution-swap.spec.ts +69 -0
  150. package/tests/profile-resolution.spec.ts +2535 -0
  151. package/tests/profile.spec.ts +70 -0
  152. package/tests/project-registry.spec.ts +81 -0
  153. package/tests/prompt-budget.spec.ts +58 -0
  154. package/tests/real-home-guard.spec.ts +178 -0
  155. package/tests/session-bridge.spec.ts +316 -0
  156. package/tests/start-source.spec.ts +65 -0
  157. package/tests/system-prompt-shape.spec.ts +95 -0
  158. package/tests/three-levels.spec.ts +84 -0
  159. package/tests/tool-gateway.spec.ts +116 -0
  160. package/tests/tool-schemas.spec.ts +41 -0
  161. package/tests/web-favicon.spec.ts +42 -0
  162. package/tests/web-port.spec.ts +38 -0
  163. package/tests/web-startup-hold.spec.ts +79 -0
  164. package/tsconfig.json +24 -0
  165. package/tsdown.config.ts +2 -0
  166. package/vitest.config.ts +18 -0
  167. package/README.md +0 -3
@@ -0,0 +1,99 @@
1
+ /*
2
+ * Ported from DeepSeek Harness, packages/boot/app-boot/src/profile-resolution/service.ts at dsh-v0.2.0-rc.2 (639ed01539, MIT,
3
+ * Copyright (c) 2026 DeepSeek; see THIRD_PARTY_NOTICES.md). Deviation: the class extends the original `PluginPackages`, so every
4
+ * consumer of the `pluginPackages` service (the plugin inventories, the plugin manager, the typert loader) keeps its type and its
5
+ * inherited `metaOf`, and constructs it with no resolution, so the original installs nothing; the interception is the port's in
6
+ * ./resolver.ts, which needs no native add-on. Second deviation: a resolve hook registered after the interception names what replaces a
7
+ * framework import from before the framework moved to acrylblends (./moved-framework.ts), and is deregistered with it.
8
+ */
9
+
10
+ /** Package metadata resolved through one runtime interception. */
11
+
12
+ import { existsSync, readFileSync } from 'node:fs'
13
+ import { createRequire } from 'node:module'
14
+ import { join } from 'node:path'
15
+ import type { Context } from '@deepseek-ai/cordis'
16
+ import { PluginPackages, type PluginPackage, type PluginPackagesConfig, type RuntimeResolution } from '@deepseek-ai/dsh-app-boot'
17
+ import { registerMovedFrameworkImports } from './moved-framework.ts'
18
+ import {
19
+ barePackageName,
20
+ installRuntimeInterception,
21
+ registerWorkerResolution,
22
+ type RuntimeInterception,
23
+ } from './resolver.ts'
24
+
25
+ function readPackage(dir: string, fallbackName: string): PluginPackage | undefined {
26
+ const manifestPath = join(dir, 'package.json')
27
+ if (!existsSync(manifestPath)) return undefined
28
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as Record<string, unknown>
29
+ const name = manifest.name
30
+ const version = manifest.version
31
+ return {
32
+ name: typeof name === 'string' ? name : fallbackName,
33
+ version: typeof version === 'string' ? version : undefined,
34
+ dir,
35
+ manifestPath,
36
+ manifest,
37
+ }
38
+ }
39
+
40
+ /** Package lookup shared by metadata consumers in one profile process, on Node's public module hooks. */
41
+ export class ProfilePluginPackages extends PluginPackages {
42
+ private table = new Map<string, PluginPackage | undefined>()
43
+ private readonly routing: RuntimeInterception | undefined
44
+ private disposeWorkers: (() => void) | undefined
45
+
46
+ constructor(ctx: Context, config: PluginPackagesConfig = {}) {
47
+ super(ctx, {})
48
+ if (config.resolution === undefined) return
49
+ const interception = installRuntimeInterception(config.resolution)
50
+ this.disposeWorkers = registerWorkerResolution(config.resolution)
51
+ this.routing = interception
52
+ // Registered after the interception, so an old framework import that the profile cannot resolve fails with what replaces it.
53
+ const movedImports = registerMovedFrameworkImports()
54
+ ctx.effect(() => () => {
55
+ movedImports.deregister()
56
+ this.disposeWorkers?.()
57
+ interception.dispose()
58
+ }, 'profile package resolution')
59
+ }
60
+
61
+ /**
62
+ * Publish a complete successor generation for this process and subsequently created Workers.
63
+ * Linked roots may be removed without unloading modules or clearing Node caches.
64
+ * @param successor - fully constructed generation accepted by {@link RuntimeInterception.replace}.
65
+ */
66
+ override replace(successor: RuntimeResolution): void {
67
+ if (this.routing === undefined) throw new Error('plugin-packages: runtime resolution is not installed')
68
+ this.routing.replace(successor)
69
+ this.table = new Map()
70
+ this.disposeWorkers?.()
71
+ this.disposeWorkers = registerWorkerResolution(successor)
72
+ }
73
+
74
+ /**
75
+ * Locate the package named by a specifier without requiring a package export.
76
+ * @param specifier - module specifier whose package owns the requested module.
77
+ * @param parentURL - URL whose Node lookup order applies.
78
+ * @returns the parsed package, or undefined when no package owns the request.
79
+ */
80
+ override packageOf(specifier: string, parentURL: string): PluginPackage | undefined {
81
+ const name = barePackageName(specifier)
82
+ if (name === undefined) return undefined
83
+ const dir = this.routing === undefined
84
+ ? packageDirFromParent(name, parentURL)
85
+ : this.routing.packageDir(name, parentURL)
86
+ if (dir === undefined) return undefined
87
+ const key = JSON.stringify({ dir, name })
88
+ if (!this.table.has(key)) this.table.set(key, readPackage(dir, name))
89
+ return this.table.get(key)
90
+ }
91
+ }
92
+
93
+ function packageDirFromParent(name: string, parentURL: string): string | undefined {
94
+ for (const searchPath of createRequire(parentURL).resolve.paths(name) as string[]) {
95
+ const candidate = join(searchPath, name)
96
+ if (existsSync(join(candidate, 'package.json'))) return candidate
97
+ }
98
+ return undefined
99
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * How big the model's fixed context is: the system prompt by section, and every tool definition, per surface.
3
+ *
4
+ * Pure measurement over what `captureSystemPrompt` returns, so it needs no engine. Sizes are in characters
5
+ * (exact, deterministic) with an estimated token count next to them; the estimate uses one documented ratio,
6
+ * so it is for comparing changes, not for billing. The committed ceilings (`plugins/system-prompt/drift/
7
+ * budget.json`) make growth a deliberate decision.
8
+ */
9
+
10
+ import type { CapturedSystemPrompt } from './system-prompt-capture.ts'
11
+
12
+ /**
13
+ * Characters per token for this English-and-JSON mix. Calibrated once on the tool definitions, which are comparable, against the owner's measurement of the
14
+ * ACRYL Web first turn (tool definitions about 8.7K tokens for 29,208 characters). The UI's system-prompt figure (about 4.6K) is larger than the
15
+ * captured system message alone because it also counts what the workspace adds (instruction files, skill catalog), which this does not capture.
16
+ */
17
+ export const CHARS_PER_TOKEN = 3.4
18
+
19
+ export interface SizedItem {
20
+ readonly name: string
21
+ readonly chars: number
22
+ }
23
+
24
+ export interface PromptBudget {
25
+ readonly sections: readonly SizedItem[]
26
+ readonly tools: readonly SizedItem[]
27
+ readonly systemChars: number
28
+ readonly toolsChars: number
29
+ }
30
+
31
+ /** Sections whose text names this machine (a checkout path, the working directory), so their size is not part of the budget. */
32
+ export const MACHINE_SPECIFIC_SECTIONS: ReadonlySet<string> = new Set(['harness_source', 'cwd'])
33
+
34
+ /** The system prompt's size without the machine-specific sections: the same on every checkout. */
35
+ export function stableSystemChars(budget: PromptBudget): number {
36
+ return budget.sections.filter(section => !MACHINE_SPECIFIC_SECTIONS.has(section.name)).reduce((sum, section) => sum + section.chars, 0)
37
+ }
38
+
39
+ /** The ceiling to record for a measurement: its size rounded up to the next 100 characters. */
40
+ export function ceilingsFor(budget: PromptBudget): BudgetCeilings {
41
+ const up = (chars: number): number => Math.ceil(chars / 100) * 100
42
+ return { systemChars: up(stableSystemChars(budget)), toolsChars: up(budget.toolsChars) }
43
+ }
44
+
45
+ export function estimateTokens(chars: number): number {
46
+ return Math.round(chars / CHARS_PER_TOKEN)
47
+ }
48
+
49
+ /** Split the assembled prompt into its identity paragraph and its `<tag>...</tag>` sections. */
50
+ export function splitSections(system: string): SizedItem[] {
51
+ const sections: SizedItem[] = []
52
+ const tag = /<([a-z_][a-z0-9_-]*)>\n?([\s\S]*?)\n?<\/\1>/g
53
+ let cursor = 0
54
+ for (const match of system.matchAll(tag)) {
55
+ const index = match.index
56
+ const head = system.slice(cursor, index).trim()
57
+ if (head !== '') sections.push({ name: cursor === 0 ? 'identity' : 'untagged', chars: head.length })
58
+ sections.push({ name: match[1] ?? 'section', chars: match[0].length })
59
+ cursor = index + match[0].length
60
+ }
61
+ const tail = system.slice(cursor).trim()
62
+ if (tail !== '') sections.push({ name: cursor === 0 ? 'identity' : 'untagged', chars: tail.length })
63
+ return sections
64
+ }
65
+
66
+ export function measurePromptBudget(captured: CapturedSystemPrompt): PromptBudget {
67
+ const tools = captured.tools
68
+ .map(tool => ({ name: tool.name, chars: JSON.stringify(tool.definition).length }))
69
+ .sort((a, b) => b.chars - a.chars || a.name.localeCompare(b.name))
70
+ return {
71
+ sections: splitSections(captured.system),
72
+ tools,
73
+ systemChars: captured.system.length,
74
+ toolsChars: tools.reduce((sum, tool) => sum + tool.chars, 0),
75
+ }
76
+ }
77
+
78
+ /** The ceilings the drift test enforces, per surface. */
79
+ export interface BudgetCeilings {
80
+ readonly systemChars: number
81
+ readonly toolsChars: number
82
+ }
83
+
84
+ /** @returns what exceeds its ceiling, in words; empty when within budget. */
85
+ export function overBudget(budget: PromptBudget, ceilings: BudgetCeilings): string[] {
86
+ const problems: string[] = []
87
+ const system = stableSystemChars(budget)
88
+ if (system > ceilings.systemChars) {
89
+ problems.push(`system prompt is ${String(system)} characters, over its ceiling of ${String(ceilings.systemChars)}`)
90
+ }
91
+ if (budget.toolsChars > ceilings.toolsChars) {
92
+ problems.push(`tool definitions are ${String(budget.toolsChars)} characters, over their ceiling of ${String(ceilings.toolsChars)}`)
93
+ }
94
+ return problems
95
+ }
96
+
97
+ const row = (item: SizedItem): string => `| \`${item.name}\` | ${String(item.chars)} | ${String(estimateTokens(item.chars))} |`
98
+
99
+ /** Markdown of the per-section and per-tool table for each surface. */
100
+ export function renderBudgetDoc(bySurface: Readonly<Record<string, PromptBudget>>): string {
101
+ const lines = [
102
+ '# System prompt and tool budget',
103
+ '',
104
+ `<!-- Generated by the system-prompt capture (see README.md). Do not edit; regenerate. Tokens are estimated at ${String(CHARS_PER_TOKEN)} characters per token. -->`,
105
+ '',
106
+ 'What the model is sent before the user says anything: the assembled system prompt (by section) and every tool definition (name, description and parameter schema).',
107
+ 'Characters are exact; tokens are an estimate for comparing changes. Ceilings live in `plugins/system-prompt/drift/budget.json`.',
108
+ '',
109
+ ]
110
+ for (const [surface, budget] of Object.entries(bySurface)) {
111
+ lines.push(`## ${surface}`, '',
112
+ `Total: system prompt ${String(budget.systemChars)} chars (about ${String(estimateTokens(budget.systemChars))} tokens), tool definitions ${String(budget.toolsChars)} chars (about ${String(estimateTokens(budget.toolsChars))} tokens), ${String(budget.tools.length)} tools.`,
113
+ '', '### System prompt by section', '', '| Section | Chars | Est. tokens |', '| --- | ---: | ---: |',
114
+ ...budget.sections.map(row), '', '### Tool definitions, largest first', '', '| Tool | Chars | Est. tokens |', '| --- | ---: | ---: |',
115
+ ...budget.tools.map(row), '')
116
+ }
117
+ return lines.join('\n')
118
+ }
@@ -0,0 +1,350 @@
1
+ import type { Context } from '@deepseek-ai/cordis'
2
+ import { installModelSelection, type Agent, type AgentHandle, type AssistantStreamFrame, type ModelSelectionRef } from '@deepseek-ai/dsh-agent'
3
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
4
+ import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
5
+ import type {} from '@deepseek-ai/dsh-agent-default-model'
6
+ import type {} from '@deepseek-ai/dsh-session-persistence'
7
+
8
+ export type { AssistantStreamFrame }
9
+ import type {
10
+ AcrylSessionAttachment,
11
+ AcrylSessionSnapshot,
12
+ AcrylSessionSubscription,
13
+ AcrylToolProjection,
14
+ AcrylTranscriptItem,
15
+ } from '@acryldev/control'
16
+
17
+ export interface AcrylSessionBridgeOptions {
18
+ readonly profile: string
19
+ readonly generationId: string
20
+ readonly attachment: AcrylSessionAttachment
21
+ readonly cwd: string
22
+ }
23
+
24
+ export interface AcrylSessionEventSubscription {
25
+ dispose(): Promise<void>
26
+ }
27
+
28
+ export interface AcrylSessionBridge {
29
+ open(resumeSessionId?: string): Promise<string>
30
+ snapshot(sessionId: string): Promise<AcrylSessionSnapshot>
31
+ /** The full durable event log for one session — the surface's replay/seed source. */
32
+ events(sessionId: string): readonly SessionEvent[]
33
+ subscribe(
34
+ sessionId: string,
35
+ listener: (snapshot: AcrylSessionSnapshot) => void,
36
+ onError?: (error: Error) => void,
37
+ ): Promise<AcrylSessionSubscription>
38
+ /** Live durable-log events for one active session (streaming presentation seam). */
39
+ subscribeEvents(
40
+ sessionId: string,
41
+ listener: (event: SessionEvent) => void,
42
+ ): Promise<AcrylSessionEventSubscription>
43
+ /**
44
+ * Process-local live assistant-stream frames (start/chunk/end) for one
45
+ * active session. Session format v2 no longer persists per-token
46
+ * `assistant/chunk` events in the durable log — `agent/assistant-stream`
47
+ * is the intentionally process-local replacement for in-progress-typing
48
+ * presentation; the durable `assistant/message`/`assistant/attempt`
49
+ * settlement (delivered via `subscribeEvents`) carries the same stream
50
+ * for replay once the attempt settles.
51
+ */
52
+ subscribeAssistantStream(
53
+ sessionId: string,
54
+ listener: (frame: AssistantStreamFrame) => void,
55
+ ): Promise<AcrylSessionEventSubscription>
56
+ submitPrompt(input: { readonly sessionId: string; readonly text: string }): Promise<void>
57
+ /**
58
+ * Switch an already-open session's live model. `agentOptions.provider`/`model`
59
+ * are a one-time construction input to `ctx.agents.create` — not a live
60
+ * setting — so this is the only thing that changes what a running session
61
+ * sends its next request to (`ModelSelectionRef` installed on the agent's
62
+ * own scoped context via `installModelSelection`, per-step prompt assembly
63
+ * reads it fresh).
64
+ */
65
+ selectModel(input: { readonly sessionId: string; readonly provider: string; readonly model: string }): Promise<void>
66
+ cancel(sessionId: string): Promise<void>
67
+ dispose(): Promise<void>
68
+ }
69
+
70
+ function contentText(content: readonly { readonly type: string; readonly text?: string }[]): string {
71
+ return content
72
+ .filter((block): block is { readonly type: 'text'; readonly text: string } => {
73
+ return block.type === 'text' && typeof block.text === 'string'
74
+ })
75
+ .map(block => block.text)
76
+ .join('')
77
+ }
78
+
79
+ function transcript(events: readonly SessionEvent[]): readonly AcrylTranscriptItem[] {
80
+ const items: AcrylTranscriptItem[] = []
81
+ for (const event of events) {
82
+ if (event.type === 'user/message' && event.data.source.kind === 'user') {
83
+ const text = contentText(event.data.content)
84
+ if (text !== '') items.push(Object.freeze({ id: `event-${event.seq}`, author: 'user', text }))
85
+ }
86
+ if (event.type === 'assistant/message') {
87
+ const text = contentText(event.data.message.content)
88
+ if (text !== '') items.push(Object.freeze({ id: `event-${event.seq}`, author: 'assistant', text }))
89
+ }
90
+ }
91
+ return Object.freeze(items)
92
+ }
93
+
94
+ function tools(events: readonly SessionEvent[]): readonly AcrylToolProjection[] {
95
+ const current = new Map<string, AcrylToolProjection>()
96
+ for (const event of events) {
97
+ if (event.type === 'tool/call') {
98
+ current.set(event.data.callId, Object.freeze({
99
+ callId: event.data.callId,
100
+ name: event.data.name,
101
+ status: 'running',
102
+ }))
103
+ }
104
+ if (event.type === 'tool/result') {
105
+ const callId = event.data.message.source.callId
106
+ const existing = current.get(callId)
107
+ if (existing !== undefined) {
108
+ current.set(callId, Object.freeze({ ...existing, status: 'succeeded' }))
109
+ }
110
+ }
111
+ }
112
+ return Object.freeze([...current.values()])
113
+ }
114
+
115
+ function status(agent: Agent): AcrylSessionSnapshot['agentStatus'] {
116
+ return agent.status === 'running' ? 'running' : 'idle'
117
+ }
118
+
119
+ /**
120
+ * Runtime-owned adapter over one native DSH agent/session. It creates or resumes
121
+ * the native agent and derives every presentation value from its durable log.
122
+ */
123
+ export function createAcrylSessionBridge(
124
+ ctx: Context,
125
+ options: AcrylSessionBridgeOptions,
126
+ ): AcrylSessionBridge {
127
+ const handles = new Map<string, AgentHandle>()
128
+ const modelSelections = new Map<string, ModelSelectionRef>()
129
+ const modelSelectionDisposers = new Map<string, () => void>()
130
+ const subscribers = new Map<string, Set<(snapshot: AcrylSessionSnapshot) => void>>()
131
+ const eventListeners = new Map<string, Set<(event: SessionEvent) => void>>()
132
+ const assistantStreamListeners = new Map<string, Set<(frame: AssistantStreamFrame) => void>>()
133
+ let disposed = false
134
+
135
+ const notify = (sessionId: string): void => {
136
+ const listeners = subscribers.get(sessionId)
137
+ if (listeners === undefined) return
138
+ void snapshot(sessionId).then((next) => {
139
+ for (const listener of listeners) {
140
+ try {
141
+ listener(next)
142
+ } catch {
143
+ // A presentation listener cannot disrupt durable session delivery.
144
+ }
145
+ }
146
+ })
147
+ }
148
+ const offSessionEvent = ctx.on('session/event', (session, event) => {
149
+ if (!handles.has(session.id)) return
150
+ notify(session.id)
151
+ const listeners = eventListeners.get(session.id)
152
+ if (listeners === undefined) return
153
+ for (const listener of listeners) {
154
+ try {
155
+ listener(event)
156
+ } catch {
157
+ // A presentation listener cannot disrupt durable session delivery.
158
+ }
159
+ }
160
+ })
161
+ // `agent/assistant-stream` is process-local and dispatched per-agent by
162
+ // `@deepseek-ai/dsh-scope`; `{ global: true }` receives every agent's
163
+ // frames and this bridge filters to the sessions it owns, matching the
164
+ // pattern `dsh-api-session-controller`'s own history/follow code uses for
165
+ // the same event.
166
+ const offAssistantStream = ctx.on('agent/assistant-stream', ({ agent, frame }) => {
167
+ if (!handles.has(agent.session.id)) return
168
+ const listeners = assistantStreamListeners.get(agent.session.id)
169
+ if (listeners === undefined) return
170
+ for (const listener of listeners) {
171
+ try {
172
+ listener(frame)
173
+ } catch {
174
+ // A presentation listener cannot disrupt durable session delivery.
175
+ }
176
+ }
177
+ }, { global: true })
178
+ // The agent's idle/running transition is not a durable event: a turn's last event is written while the agent is still running, and the
179
+ // return to idle follows with nothing logged, so a subscriber refreshed only on events kept showing "running" after every turn.
180
+ const offAgentStatus = ctx.on('agent/status', ({ agent }) => {
181
+ if (handles.has(agent.session.id)) notify(agent.session.id)
182
+ }, { global: true })
183
+
184
+ const snapshot = async (sessionId: string): Promise<AcrylSessionSnapshot> => {
185
+ const agent = agentFor(sessionId)
186
+ return Object.freeze({
187
+ profile: options.profile,
188
+ generationId: options.generationId,
189
+ attachment: options.attachment,
190
+ sessionId: agent.id,
191
+ agentStatus: status(agent),
192
+ transcript: transcript(agent.session.snapshotEvents()),
193
+ tools: tools(agent.session.snapshotEvents()),
194
+ })
195
+ }
196
+
197
+ const agentFor = (sessionId: string): Agent => {
198
+ if (disposed) throw new Error('ACRYL session bridge is disposed')
199
+ const handle = handles.get(sessionId)
200
+ if (handle === undefined) throw new Error(`ACRYL session ${sessionId} is not active`)
201
+ return handle.agent
202
+ }
203
+
204
+ return Object.freeze({
205
+ async open(resumeSessionId?: string): Promise<string> {
206
+ if (disposed) throw new Error('ACRYL session bridge is disposed')
207
+ if (handles.size !== 0) throw new Error('ACRYL session bridge already has an active session')
208
+ const defaultModel = ctx.get('agentDefaultModel')
209
+ if (defaultModel === undefined) throw new Error('ACRYL profile has no default agent model')
210
+ const selection = defaultModel.currentSelection()
211
+ const handle = resumeSessionId === undefined
212
+ ? await ctx.agents.create({
213
+ sessionId: SessionId(`acryl-session-${crypto.randomUUID()}`),
214
+ meta: { cwd: options.cwd },
215
+ agentOptions: { provider: selection.provider, model: selection.model },
216
+ })
217
+ : await ctx.agents.resume({
218
+ resumeSessionId: SessionId(resumeSessionId),
219
+ agentOptions: { provider: selection.provider, model: selection.model },
220
+ })
221
+ handles.set(handle.agent.id, handle)
222
+ const ref: ModelSelectionRef = { current: undefined, assembled: undefined }
223
+ modelSelectionDisposers.set(handle.agent.id, installModelSelection(handle.agent.ctx, ref))
224
+ modelSelections.set(handle.agent.id, ref)
225
+ return handle.agent.id
226
+ },
227
+ snapshot,
228
+ events(sessionId: string): readonly SessionEvent[] {
229
+ return agentFor(sessionId).session.snapshotEvents()
230
+ },
231
+ async subscribe(
232
+ sessionId: string,
233
+ listener: (snapshot: AcrylSessionSnapshot) => void,
234
+ _onError?: (error: Error) => void,
235
+ ): Promise<AcrylSessionSubscription> {
236
+ agentFor(sessionId)
237
+ const listeners = subscribers.get(sessionId) ?? new Set()
238
+ subscribers.set(sessionId, listeners)
239
+ listeners.add(listener)
240
+ try {
241
+ listener(await snapshot(sessionId))
242
+ } catch {
243
+ // Presentation listeners cannot disrupt durable session delivery.
244
+ }
245
+ let active = true
246
+ return Object.freeze({
247
+ whenError(): Promise<Error> { return new Promise<Error>(() => {}) },
248
+ async dispose(): Promise<void> {
249
+ if (!active) return
250
+ active = false
251
+ listeners.delete(listener)
252
+ if (listeners.size === 0) subscribers.delete(sessionId)
253
+ },
254
+ })
255
+ },
256
+ async subscribeEvents(
257
+ sessionId: string,
258
+ listener: (event: SessionEvent) => void,
259
+ ): Promise<AcrylSessionEventSubscription> {
260
+ agentFor(sessionId)
261
+ const listeners = eventListeners.get(sessionId) ?? new Set()
262
+ eventListeners.set(sessionId, listeners)
263
+ listeners.add(listener)
264
+ let active = true
265
+ return Object.freeze({
266
+ async dispose(): Promise<void> {
267
+ if (!active) return
268
+ active = false
269
+ listeners.delete(listener)
270
+ if (listeners.size === 0) eventListeners.delete(sessionId)
271
+ },
272
+ })
273
+ },
274
+ async subscribeAssistantStream(
275
+ sessionId: string,
276
+ listener: (frame: AssistantStreamFrame) => void,
277
+ ): Promise<AcrylSessionEventSubscription> {
278
+ agentFor(sessionId)
279
+ const listeners = assistantStreamListeners.get(sessionId) ?? new Set()
280
+ assistantStreamListeners.set(sessionId, listeners)
281
+ listeners.add(listener)
282
+ let active = true
283
+ return Object.freeze({
284
+ async dispose(): Promise<void> {
285
+ if (!active) return
286
+ active = false
287
+ listeners.delete(listener)
288
+ if (listeners.size === 0) assistantStreamListeners.delete(sessionId)
289
+ },
290
+ })
291
+ },
292
+ async submitPrompt(input: { readonly sessionId: string; readonly text: string }): Promise<void> {
293
+ const agent = agentFor(input.sessionId)
294
+ if (input.text.trim() === '') throw new Error('ACRYL prompt must not be empty')
295
+ const accepted = new Promise<void>((resolve) => {
296
+ const off = ctx.on('session/event', (session, event) => {
297
+ if (session !== agent.session || event.type !== 'user/message') return
298
+ off()
299
+ resolve()
300
+ })
301
+ })
302
+ agent.followup(createUserMessage({
303
+ content: [{ type: 'text', text: input.text }],
304
+ source: { kind: 'user' },
305
+ }))
306
+ await accepted
307
+ },
308
+ async selectModel(input: { readonly sessionId: string; readonly provider: string; readonly model: string }): Promise<void> {
309
+ agentFor(input.sessionId)
310
+ const ref = modelSelections.get(input.sessionId)
311
+ if (ref === undefined) throw new Error(`ACRYL session ${input.sessionId} has no installed model selection`)
312
+ ref.current = { provider: input.provider, model: input.model }
313
+ },
314
+ async cancel(sessionId: string): Promise<void> {
315
+ agentFor(sessionId).cancel({ kind: 'user' })
316
+ },
317
+ async dispose(): Promise<void> {
318
+ if (disposed) return
319
+ disposed = true
320
+ offSessionEvent()
321
+ offAssistantStream()
322
+ offAgentStatus()
323
+ subscribers.clear()
324
+ eventListeners.clear()
325
+ assistantStreamListeners.clear()
326
+ for (const dispose of modelSelectionDisposers.values()) dispose()
327
+ modelSelectionDisposers.clear()
328
+ modelSelections.clear()
329
+ // Durable continuity: idle the turn, checkpoint the session log, then
330
+ // release the native handle. Mirror of Tomo's shutdown sequence, owned
331
+ // here so every surface gets the same durability guarantee.
332
+ const activeHandles = [...handles.values()]
333
+ handles.clear()
334
+ const sessions = ctx.get('sessions')
335
+ for (const handle of activeHandles) {
336
+ try {
337
+ await handle.agent.whenIdle()
338
+ } catch {
339
+ // A disposing agent has no obligation to be idle; proceed to release.
340
+ }
341
+ try {
342
+ await sessions?.flush(handle.agent.session)
343
+ } catch {
344
+ // Flush is best-effort on dispose; persistence already ran per event.
345
+ }
346
+ }
347
+ await Promise.all(activeHandles.map(handle => handle.dispose()))
348
+ },
349
+ })
350
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * A durable, cross-surface debug log for ACRYL sessions.
3
+ *
4
+ * Cordis's own `ctx.logger` already carries every structured log record any
5
+ * plugin emits, but nothing in this stack persisted it anywhere — a failure
6
+ * like a vendored provider's OAuth error only ever reached the terminal
7
+ * transcript, gone the moment the pane scrolled or the process exited. This
8
+ * registers one JSONL file exporter on `ctx.logger` per surface (CLI/TUI,
9
+ * web, and — once wired there too — the desktop GUI), so `error`/`warn`
10
+ * records (and everything, when `ACRYL_LOG_LEVEL=debug`) survive the session
11
+ * and can be read back after the fact instead of re-derived from a
12
+ * screenshot.
13
+ *
14
+ * @module @acryldev/harness-runtime/session-log-exporter
15
+ */
16
+
17
+ import { appendFileSync, mkdirSync } from 'node:fs'
18
+ import { join } from 'node:path'
19
+ import type { Context } from '@deepseek-ai/cordis'
20
+
21
+ export interface InstallSessionLogExporterOptions {
22
+ /** Which ACRYL surface this process is (`tui`, `web`, `desktop`) — becomes part of the log filename. */
23
+ readonly surface: string
24
+ /** The app instance's harness home (`instance.dshHome`): where `logs/` lives. Always explicit, never resolved from the environment here. */
25
+ readonly dshHome: string
26
+ }
27
+
28
+ const LOGGER_LEVEL_WARN = 2
29
+ const LOGGER_LEVEL_DEBUG = 3
30
+
31
+ /**
32
+ * Register the file exporter for this process's lifetime. `ctx.logger.exporter()`
33
+ * already ties its own disposal to the fiber that registers it (see
34
+ * `LoggerService.exporter` in `@deepseek-ai/cordis`), so this needs no extra
35
+ * `ctx.effect()` wrapper of its own.
36
+ * @param ctx - the plugin context whose `ctx.logger` gains the exporter.
37
+ * @param options - which surface/home this log file belongs to.
38
+ */
39
+ export function installSessionLogExporter(ctx: Context, options: InstallSessionLogExporterOptions): void {
40
+ const { dshHome } = options
41
+ const logDir = join(dshHome, 'logs')
42
+ try {
43
+ mkdirSync(logDir, { recursive: true, mode: 0o700 })
44
+ } catch {
45
+ return // best-effort diagnostics only; a session must never fail to start over this
46
+ }
47
+ const day = new Date().toISOString().slice(0, 10)
48
+ const logFile = join(logDir, `acryl-${options.surface}-${day}.jsonl`)
49
+ const threshold = process.env.ACRYL_LOG_LEVEL === 'debug' ? LOGGER_LEVEL_DEBUG : LOGGER_LEVEL_WARN
50
+
51
+ ctx.logger.exporter({
52
+ export(message) {
53
+ if (message.level > threshold) return
54
+ try {
55
+ appendFileSync(logFile, `${JSON.stringify({
56
+ ts: new Date(message.ts).toISOString(),
57
+ type: message.type,
58
+ name: message.name,
59
+ args: message.args.map(arg => (arg instanceof Error
60
+ ? { message: arg.message, stack: arg.stack, name: arg.name }
61
+ : arg)),
62
+ })}\n`, { mode: 0o600 })
63
+ } catch {
64
+ // best-effort: a write failure here must never take a session down
65
+ }
66
+ },
67
+ })
68
+ }