index.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /**
  2. * Model-facing Cordis runtime/package inspection, define, run, stop, and remove tools.
  3. * @module @deepseek-ai/dsh-tool-cordis
  4. */
  5. import type { Context } from '@deepseek-ai/cordis'
  6. import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'
  7. import {
  8. CordisDynamicPackageId, CordisDynamicPluginId,
  9. } from '@deepseek-ai/dsh-cordis-host-runner'
  10. import type { DynamicCordisReference } from '@deepseek-ai/dsh-cordis-host-runner'
  11. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  12. import type { JsonValue } from '@deepseek-ai/dsh-session'
  13. import type { UserMessage } from '@deepseek-ai/dsh-session'
  14. import { defineTool } from '@deepseek-ai/dsh-tools'
  15. import type { ToolExecution } from '@deepseek-ai/dsh-tools'
  16. import type {} from '@deepseek-ai/dsh-system-prompt'
  17. import { missingServices, providedServices } from './inspect.ts'
  18. import {
  19. presentDefineCall, presentInspectListCall, presentInspectQueryCall, presentInspectSelfCall, presentRunCall,
  20. presentStopCall, presentUndefineCall,
  21. } from './present.ts'
  22. import { CORDIS_SYSTEM_PROMPT } from './prompt.ts'
  23. import { hostInspectProviders } from './providers.ts'
  24. export const name = 'tool-cordis'
  25. export const inject = ['tools', 'systemPrompt', 'dynamicCordisRunner', 'cordisInspect']
  26. function requireAgent(exec: ToolExecution): Agent {
  27. if (exec.agent === undefined) throw new Error('Cordis dynamic tools require an Agent-backed session')
  28. return exec.agent
  29. }
  30. /** Register the Cordis tools and explicit `@pluginId` context injection. */
  31. export function apply(ctx: Context): void {
  32. ctx.systemPrompt.section({ name: 'tool:cordis', order: 115.5, text: CORDIS_SYSTEM_PROMPT })
  33. for (const provider of hostInspectProviders(ctx)) {
  34. ctx.effect(() => ctx.cordisInspect.register(provider), `tool-cordis: inspect ${provider.manifest.id}`)
  35. }
  36. ctx.tools.register(defineTool({
  37. name: 'cordis_inspect_list',
  38. description:
  39. 'List every Cordis Inspect Provider currently known to the Host, including local Host Providers and the latest '
  40. + 'manifests synchronized from the Client. Each entry includes its platform, purpose, read-only methods, and '
  41. + 'input/output schemas. Call this Tool before creating or modifying a Package, then select the provider and '
  42. + 'method for cordis_inspect_query from its result. Do not guess names or treat an Inspect method as a business '
  43. + 'Service that Plugin code can call.',
  44. parameters: {},
  45. output: {
  46. schema: { type: 'json' },
  47. render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
  48. },
  49. execute(_args, _exec): Promise<JsonValue> {
  50. return Promise.resolve({ providers: ctx.cordisInspect.list() } as unknown as JsonValue)
  51. },
  52. presentCall: presentInspectListCall,
  53. }))
  54. ctx.tools.register(defineTool({
  55. name: 'cordis_inspect_query',
  56. description:
  57. 'Run a read-only query explicitly declared by an Inspect Provider. platform, provider, and method must come '
  58. + 'from cordis_inspect_list, and input must satisfy that method\'s schema. Use this Tool before cordis_define '
  59. + 'to read exact Service methods, Event modes, Builtin signatures, Tool schemas, theme tokens, or live Slot '
  60. + 'trees and props. Host queries run locally. A Client query waits for the first valid page response and '
  61. + 'remains pending until a page answers or the Tool is cancelled. This Tool cannot invoke business Service '
  62. + 'methods or modify the runtime. For Service.listService and Event.listEvents, query without input to navigate '
  63. + 'the compact signature directory, then query the exact service or event for its structured contract and '
  64. + 'referenced types. For Slots.listSubTree, query without root to navigate the compact tree, then query the '
  65. + 'exact root for its complete registration contract and props.',
  66. parameters: {
  67. platform: { type: 'string', required: true, enum: ['host', 'client'], description: 'Runtime platform that owns the Provider.' },
  68. provider: { type: 'string', required: true, description: 'Exact Provider ID returned by cordis_inspect_list.' },
  69. method: { type: 'string', required: true, description: 'Exact method name declared by the Provider manifest.' },
  70. input: { type: 'json', description: 'Optional query input; it must satisfy the method input schema.' },
  71. },
  72. output: {
  73. schema: { type: 'json' },
  74. render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
  75. },
  76. async execute(args, exec) {
  77. const data = await ctx.cordisInspect.query(
  78. args.platform,
  79. args.provider,
  80. args.method,
  81. args.input,
  82. requireAgent(exec),
  83. exec.signal,
  84. )
  85. return { platform: args.platform, provider: args.provider, method: args.method, data }
  86. },
  87. presentCall: presentInspectQueryCall,
  88. }))
  89. ctx.tools.register(defineTool({
  90. name: 'cordis_inspect_self',
  91. description:
  92. 'Inspect dynamic Cordis objects owned by the current Session at increasing levels of detail. With no IDs, '
  93. + 'list only Plugin summaries. With pluginId alone, return version pointers, the latest Run, and every Package '
  94. + 'summary. Only pluginId plus packageId returns that immutable Package\'s Host/Client source and runtime '
  95. + 'diagnostics. packageId cannot be supplied alone. Query an exact Package before handling @pluginId, repairing '
  96. + 'an asynchronous failure, or defining an updated version. This Tool is read-only: it neither executes code '
  97. + 'nor changes version pointers.',
  98. parameters: {
  99. pluginId: { type: 'string', description: 'Stable Plugin ID returned by cordis_define or injected by @pluginId; omit it to list every current Plugin.' },
  100. packageId: { type: 'string', description: 'Exact immutable Package ID owned by pluginId; when specified, source and diagnostics are returned.' },
  101. },
  102. output: {
  103. schema: { type: 'json' },
  104. render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
  105. },
  106. execute(args, exec): Promise<JsonValue> {
  107. const agent = requireAgent(exec)
  108. if (args.packageId !== undefined && args.pluginId === undefined) {
  109. throw new Error('cordis_inspect_self packageId requires pluginId')
  110. }
  111. if (args.pluginId === undefined) {
  112. return Promise.resolve({
  113. mode: 'plugins',
  114. plugins: ctx.dynamicCordisRunner.listPlugins(agent).map(reference => selfSummary(reference)),
  115. } as unknown as JsonValue)
  116. }
  117. const pluginId = CordisDynamicPluginId(args.pluginId)
  118. if (args.packageId === undefined) {
  119. const plugin = ctx.dynamicCordisRunner.inspectPlugin(agent, pluginId)
  120. return Promise.resolve({
  121. mode: 'plugin',
  122. ...selfSummary(plugin),
  123. packages: plugin.packages.map(pkg => ({
  124. ...pkg,
  125. packageId: String(pkg.packageId),
  126. isCurrent: pkg.packageId === plugin.currentPackageId,
  127. isNext: pkg.packageId === plugin.nextPackageId,
  128. })),
  129. } as unknown as JsonValue)
  130. }
  131. return Promise.resolve(inspectSelfPackage(
  132. ctx,
  133. agent,
  134. pluginId,
  135. CordisDynamicPackageId(args.packageId),
  136. ) as unknown as JsonValue)
  137. },
  138. presentCall: presentInspectSelfCall,
  139. }))
  140. ctx.tools.register(defineTool({
  141. name: 'cordis_define',
  142. description:
  143. 'Define an immutable Cordis Package. For a new Plugin, use kind:"new" and provide only a semantic prefix of '
  144. + '3–6 lowercase English letters; the Host returns the final pluginId and packageId. To modify an existing '
  145. + 'Plugin, use kind:"existing" with its exact pluginId to append a Package without overwriting older versions. '
  146. + 'Provide at least one of code.host and code.client. Each value is a plain JavaScript function body that returns '
  147. + 'a Cordis Plugin; no TypeScript, JSX, or import transformation occurs. Query Inspect before depending on a '
  148. + 'Service, Event, Builtin, Slot, or token. Define only validates parameters and syntax and records source: it '
  149. + 'does not request approval, execute apply, or change currentPackageId. On success, call cordis_run with the '
  150. + 'returned IDs.',
  151. parameters: {
  152. plugin: {
  153. required: true,
  154. oneOf: [
  155. {
  156. type: 'object',
  157. additionalProperties: false,
  158. properties: {
  159. kind: { type: 'string', const: 'new', required: true },
  160. idPrefix: {
  161. type: 'string',
  162. required: true,
  163. description: 'Suggested semantic prefix of 3–6 lowercase English letters; the Host adds a unique numeric suffix.',
  164. },
  165. },
  166. },
  167. {
  168. type: 'object',
  169. additionalProperties: false,
  170. properties: {
  171. kind: { type: 'string', const: 'existing', required: true },
  172. pluginId: { type: 'string', required: true, description: 'Exact ID of an existing Plugin; the new Package is appended to that instance.' },
  173. },
  174. },
  175. ],
  176. },
  177. name: { type: 'string', required: true, description: 'Short, readable Package name.' },
  178. purpose: { type: 'string', required: true, description: 'One-sentence, user-facing description of the Package purpose.' },
  179. code: {
  180. type: 'object',
  181. additionalProperties: false,
  182. required: true,
  183. properties: {
  184. host: { type: 'string', description: 'Plain JavaScript function body that returns the Host-half Cordis Plugin.' },
  185. client: { type: 'string', description: 'Plain JavaScript function body that returns the browser Client-half Cordis Plugin.' },
  186. },
  187. },
  188. },
  189. output: {
  190. schema: {
  191. type: 'object',
  192. additionalProperties: false,
  193. properties: {
  194. pluginId: { type: 'string', required: true },
  195. packageId: { type: 'string', required: true },
  196. name: { type: 'string', required: true },
  197. purpose: { type: 'string', required: true },
  198. hasHostHalf: { type: 'boolean', required: true },
  199. hasClientHalf: { type: 'boolean', required: true },
  200. },
  201. },
  202. render: (_args, value) => [{
  203. type: 'text',
  204. text: `Defined ${value.pluginId}/${value.packageId} (${value.name}); it is not running yet. `
  205. + 'Use cordis_run to activate this Package.',
  206. }],
  207. presentationMeta: (_args, value) => ({ pluginId: value.pluginId, packageId: value.packageId }),
  208. },
  209. execute(args, exec) {
  210. const plugin = args.plugin.kind === 'new'
  211. ? { kind: 'new' as const, idPrefix: args.plugin.idPrefix }
  212. : { kind: 'existing' as const, pluginId: CordisDynamicPluginId(args.plugin.pluginId) }
  213. const receipt = ctx.dynamicCordisRunner.define({
  214. sessionId: requireAgent(exec).id,
  215. plugin,
  216. name: args.name,
  217. purpose: args.purpose,
  218. code: {
  219. ...args.code.host === undefined ? {} : { host: args.code.host },
  220. ...args.code.client === undefined ? {} : { client: args.code.client },
  221. },
  222. })
  223. return Promise.resolve({
  224. ...receipt,
  225. pluginId: String(receipt.pluginId),
  226. packageId: String(receipt.packageId),
  227. })
  228. },
  229. presentCall: presentDefineCall,
  230. }))
  231. ctx.tools.register(defineTool({
  232. name: 'cordis_run',
  233. description:
  234. 'Activate one exact Package of a dynamic Plugin. Use mode:"run" for the first activation, restarting '
  235. + 'currentPackageId, or rollback. When current exists, use mode:"update" to switch to a different Package, '
  236. + 'even if the Plugin is currently stopped. An unauthorized Client Package creates an approval request and '
  237. + 'returns awaiting-approval; an authorized Package returns starting and continues asynchronously in the '
  238. + 'browser. Neither result waits for the final outcome inside the Tool. currentPackageId changes only after '
  239. + 'complete success; on failure, the old current and target next remain. Asynchronous success, rejection, or '
  240. + 'technical failure is reported through state and steering. After a technical failure, read diagnostics with '
  241. + 'cordis_inspect_self, correct the same Plugin, and retry autonomously. Do not request approval again after '
  242. + 'the user rejects it.',
  243. parameters: {
  244. pluginId: { type: 'string', required: true, description: 'Stable Plugin ID returned by cordis_define.' },
  245. packageId: { type: 'string', required: true, description: 'Exact immutable Package ID to activate under that Plugin.' },
  246. mode: {
  247. type: 'string',
  248. required: true,
  249. enum: ['run', 'update'],
  250. description: 'Use run for the first activation, restarting current, or rollback; use update to switch from current to a different Package.',
  251. },
  252. },
  253. output: {
  254. schema: { type: 'json' },
  255. render: (_args, value) => {
  256. const result = requireJsonObject(value)
  257. const pluginId = requireJsonString(result, 'pluginId')
  258. const packageId = requireJsonString(result, 'packageId')
  259. const pluginRunId = requireJsonString(result, 'pluginRunId')
  260. return [{
  261. type: 'text',
  262. text: result.status === 'awaiting-approval'
  263. ? `${pluginId}/${packageId} is awaiting user approval (${pluginRunId}).`
  264. : result.status === 'starting'
  265. ? `${pluginId}/${packageId} is starting asynchronously (${pluginRunId}).`
  266. : `${pluginId}/${packageId} is running (${pluginRunId}).`,
  267. }]
  268. },
  269. presentationMeta: (_args, value) => {
  270. const result = requireJsonObject(value)
  271. return {
  272. pluginId: requireJsonString(result, 'pluginId'),
  273. packageId: requireJsonString(result, 'packageId'),
  274. pluginRunId: requireJsonString(result, 'pluginRunId'),
  275. }
  276. },
  277. },
  278. async execute(args, exec) {
  279. const agent = requireAgent(exec)
  280. const pluginId = CordisDynamicPluginId(args.pluginId)
  281. const packageId = CordisDynamicPackageId(args.packageId)
  282. const receipt = await ctx.dynamicCordisRunner.run(agent, pluginId, packageId, args.mode, exec.signal)
  283. if (!receipt.ok) throw new Error(receipt.message)
  284. if (receipt.status !== 'running') {
  285. return {
  286. status: receipt.status,
  287. pluginId: args.pluginId,
  288. packageId: args.packageId,
  289. pluginRunId: String(receipt.pluginRunId),
  290. mode: receipt.mode,
  291. ...receipt.currentPackageId === undefined ? {} : { currentPackageId: String(receipt.currentPackageId) },
  292. nextPackageId: String(receipt.nextPackageId),
  293. }
  294. }
  295. const row = ctx.dynamicCordisRunner.snapshot(agent).find(candidate => candidate.pluginId === pluginId)
  296. const fiber = row?.activeRun?.pluginRunId === receipt.pluginRunId ? row.activeRun.fiber : undefined
  297. return {
  298. status: 'running',
  299. pluginId: args.pluginId,
  300. packageId: args.packageId,
  301. pluginRunId: String(receipt.pluginRunId),
  302. currentPackageId: String(receipt.currentPackageId),
  303. ...receipt.nextPackageId === undefined ? {} : { nextPackageId: String(receipt.nextPackageId) },
  304. host: {
  305. status: fiber === undefined ? 'absent' : missingServices(ctx, fiber).length === 0 ? 'running' : 'waiting',
  306. provides: fiber === undefined ? [] : providedServices(ctx, fiber),
  307. waitingFor: fiber === undefined ? [] : missingServices(ctx, fiber),
  308. },
  309. client: {
  310. status: receipt.clientWaitingFor === undefined
  311. ? 'absent'
  312. : receipt.clientWaitingFor.length === 0 ? 'running' : 'waiting',
  313. waitingFor: [...(receipt.clientWaitingFor ?? [])],
  314. },
  315. }
  316. },
  317. presentCall: presentRunCall,
  318. }))
  319. ctx.tools.register(defineTool({
  320. name: 'cordis_stop',
  321. description:
  322. 'Stop the current Run of a dynamic Plugin and cancel unfinished approval or activation requests. Retain the '
  323. + 'Plugin, every immutable Package, grants, currentPackageId, and nextPackageId so it can later run or update '
  324. + 'directly. Stopping an already stopped Plugin succeeds idempotently. Use this Tool to disable effects '
  325. + 'temporarily; use cordis_undefine for permanent removal.',
  326. parameters: {
  327. pluginId: { type: 'string', required: true, description: 'Stable dynamic Plugin ID to stop.' },
  328. },
  329. output: {
  330. schema: { type: 'object', additionalProperties: false, properties: { pluginId: { type: 'string', required: true } } },
  331. render: (_args, value) => [{ type: 'text', text: `Dynamic Plugin ${value.pluginId} is stopped; its definition and versions remain.` }],
  332. },
  333. async execute(args, exec) {
  334. const receipt = await ctx.dynamicCordisRunner.stop(requireAgent(exec), CordisDynamicPluginId(args.pluginId))
  335. if (!receipt.ok && receipt.reason !== 'not-running') throw new Error(receipt.message)
  336. return { pluginId: args.pluginId }
  337. },
  338. presentCall: presentStopCall,
  339. }))
  340. ctx.tools.register(defineTool({
  341. name: 'cordis_undefine',
  342. description:
  343. 'Permanently remove a dynamic Plugin owned by the current Session. If it is running or awaiting approval, '
  344. + 'first stop it and cancel the request, then delete every Package, grant, and version pointer. After this '
  345. + 'returns, its pluginId, packageIds, @ reference, and Package business views are invalid; historical cards '
  346. + 'retain only a "Plugin removed" record. Do not call this Tool when versions must remain available for restart '
  347. + 'or rollback; use cordis_stop instead.',
  348. parameters: {
  349. pluginId: { type: 'string', required: true, description: 'Stable dynamic Plugin ID to remove permanently.' },
  350. },
  351. output: {
  352. schema: {
  353. type: 'object',
  354. additionalProperties: false,
  355. properties: {
  356. pluginId: { type: 'string', required: true },
  357. wasRunning: { type: 'boolean', required: true },
  358. },
  359. },
  360. render: (_args, value) => [{ type: 'text', text: `Removed dynamic Plugin ${value.pluginId} and all of its Packages.` }],
  361. },
  362. async execute(args, exec) {
  363. const receipt = await ctx.dynamicCordisRunner.undefine(requireAgent(exec), CordisDynamicPluginId(args.pluginId))
  364. if (!receipt.ok) throw new Error(receipt.message)
  365. return { pluginId: args.pluginId, wasRunning: receipt.wasRunning }
  366. },
  367. presentCall: presentUndefineCall,
  368. }))
  369. ctx.on('agent/pre-step', async ({ agent, messages, signal }, next): Promise<PreStepDecision> => {
  370. const decision = await next()
  371. if (decision.kind === 'reject') return decision
  372. const ids = referencedPluginIds(messages)
  373. if (ids.length === 0) return decision
  374. signal.throwIfAborted()
  375. const contexts = ids.map((id) => {
  376. const reference = ctx.dynamicCordisRunner.reference(agent, CordisDynamicPluginId(id))
  377. return createUserMessage({
  378. content: [{
  379. type: 'text',
  380. text: reference === undefined ? renderUnavailableReference(id) : renderReference(reference),
  381. }],
  382. source: { kind: 'plugin', plugin: name, form: 'instructions' },
  383. })
  384. })
  385. return { kind: 'enter', messages: [...decision.messages, ...contexts] }
  386. })
  387. }
  388. function requireJsonObject(value: JsonValue): Record<string, JsonValue> {
  389. if (typeof value !== 'object' || value === null || Array.isArray(value)) {
  390. throw new Error('expected a JSON object')
  391. }
  392. return value
  393. }
  394. function requireJsonString(value: Record<string, JsonValue>, key: string): string {
  395. const field = value[key]
  396. if (typeof field !== 'string') throw new Error(`expected JSON string field "${key}"`)
  397. return field
  398. }
  399. type SelfState = 'defined' | 'awaiting-approval' | 'client-pending' | 'stopped' | 'running' | 'waiting' | 'failed'
  400. function selfSummary(reference: DynamicCordisReference & { packages?: readonly unknown[] }): Record<string, JsonValue> {
  401. const latest = reference.latestRun
  402. const state = selfState(reference)
  403. return {
  404. pluginId: String(reference.pluginId),
  405. name: reference.name,
  406. packageCount: reference.packages?.length ?? 1,
  407. state,
  408. ...reference.currentPackageId === undefined ? {} : { currentPackageId: String(reference.currentPackageId) },
  409. ...reference.nextPackageId === undefined ? {} : { nextPackageId: String(reference.nextPackageId) },
  410. ...reference.activeRun === undefined ? {} : {
  411. activeRun: {
  412. pluginRunId: String(reference.activeRun.pluginRunId),
  413. packageId: String(reference.activeRun.packageId),
  414. },
  415. },
  416. ...latest?.status !== 'awaiting-approval' ? {} : {
  417. pendingApproval: {
  418. pluginRunId: String(latest.pluginRunId),
  419. packageId: String(latest.packageId),
  420. mode: latest.mode,
  421. },
  422. },
  423. }
  424. }
  425. function selfState(reference: DynamicCordisReference): SelfState {
  426. const status = reference.latestRun?.status
  427. if (status === 'awaiting-approval') return 'awaiting-approval'
  428. if (status === 'client-pending' || status === 'starting-host') return 'client-pending'
  429. if (status === 'failed' || status === 'rejected' || status === 'cancelled') return 'failed'
  430. if (status === 'waiting') return 'waiting'
  431. if (status === 'running') return 'running'
  432. if (reference.activeRun !== undefined) return 'running'
  433. return reference.currentPackageId === undefined ? 'defined' : 'stopped'
  434. }
  435. function inspectSelfPackage(
  436. ctx: Context,
  437. agent: Agent,
  438. pluginId: ReturnType<typeof CordisDynamicPluginId>,
  439. packageId: ReturnType<typeof CordisDynamicPackageId>,
  440. ): Record<string, JsonValue> {
  441. const inspected = ctx.dynamicCordisRunner.inspectPackage(agent, pluginId, packageId)
  442. const row = ctx.dynamicCordisRunner.snapshot(agent).find(candidate => candidate.pluginId === pluginId)
  443. const pkg = row?.packages.find(candidate => candidate.packageId === packageId)
  444. const active = row?.activeRun?.packageId === packageId ? row.activeRun : undefined
  445. const latest = inspected.latestRun?.packageId === packageId ? inspected.latestRun : undefined
  446. const hostWaiting = active?.fiber === undefined ? [...(latest?.host.waitingFor ?? [])] : missingServices(ctx, active.fiber)
  447. const hostStatus = pkg?.hasHostHalf !== true
  448. ? 'absent'
  449. : latest?.host.status ?? (active === undefined ? 'stopped' : hostWaiting.length === 0 ? 'running' : 'waiting')
  450. const clientStatus = pkg?.hasClientHalf !== true
  451. ? 'absent'
  452. : latest?.client.status ?? 'stopped'
  453. return {
  454. mode: 'package',
  455. plugin: selfSummary(inspected),
  456. packageId: String(packageId),
  457. name: inspected.name,
  458. purpose: inspected.purpose,
  459. code: inspected.code,
  460. runtime: {
  461. state: selfState(inspected),
  462. host: {
  463. status: hostStatus,
  464. provides: active?.fiber === undefined ? [] : providedServices(ctx, active.fiber),
  465. waitingFor: hostWaiting,
  466. handlers: active?.handlers ?? [],
  467. ...latest?.host.error === undefined ? {} : { error: latest.host.error },
  468. },
  469. client: {
  470. status: clientStatus,
  471. waitingFor: [...(latest?.client.waitingFor ?? [])],
  472. ...latest?.client.error === undefined ? {} : { error: latest.client.error },
  473. ...active?.renderFailure === undefined ? {} : { renderFailure: active.renderFailure },
  474. },
  475. },
  476. } as unknown as Record<string, JsonValue>
  477. }
  478. function referencedPluginIds(messages: readonly UserMessage[]): string[] {
  479. const found = new Set<string>()
  480. const pattern = /(?:^|\s)@([a-z]{3,6}-\d+)(?=\s|$)/g
  481. for (const message of messages) {
  482. if (message.source.kind !== 'user') continue
  483. const text = message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n')
  484. for (const match of text.matchAll(pattern)) if (match[1] !== undefined) found.add(match[1])
  485. }
  486. return [...found]
  487. }
  488. function renderReference(reference: ReturnType<Context['dynamicCordisRunner']['reference']> & {}): string {
  489. const mode = reference.currentPackageId === undefined ? 'run' : 'update'
  490. return [
  491. '<cordis_dynamic_plugin_context>',
  492. JSON.stringify(reference, null, 2),
  493. '',
  494. `The user explicitly referenced @${reference.pluginId}. Use Package ${reference.packageId} as the base for this modification.`,
  495. `Before modifying it, call cordis_inspect_self with pluginId="${reference.pluginId}" and packageId="${reference.packageId}" to read the exact metadata and source.`,
  496. `Use cordis_define with plugin.kind="existing" and the original pluginId="${reference.pluginId}" to append an immutable Package.`,
  497. `Do not create a new Plugin for this request. After cordis_define succeeds, call cordis_run mode="${mode}" with the returned packageId.`,
  498. '</cordis_dynamic_plugin_context>',
  499. ].join('\n')
  500. }
  501. function renderUnavailableReference(id: string): string {
  502. return [
  503. '<cordis_dynamic_plugin_context>',
  504. `The user explicitly referenced @${id}, but this Plugin is unavailable in the current Session.`,
  505. 'It may have been removed, belong to another Session, or have been lost when the DSH process restarted.',
  506. 'Do not claim that it was updated or silently create a replacement Plugin. Tell the user that the reference is currently unavailable.',
  507. '</cordis_dynamic_plugin_context>',
  508. ].join('\n')
  509. }