@xingular/harness 0.1.6 → 2.0.0

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 (131) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/NOTICE.md +38 -0
  3. package/README.md +139 -28
  4. package/dist/cli.js +9598 -2201
  5. package/dist/terminal-pi.js +808 -16
  6. package/docs/README.md +15 -0
  7. package/docs/decisions/ADR-0001-owned-terminal.md +87 -0
  8. package/docs/decisions/ADR-0002-native-subagent-lifecycle.md +49 -0
  9. package/docs/decisions/ADR-0003-shared-asynchronous-subagents.md +68 -0
  10. package/docs/decisions/ADR-0004-fullscreen-terminal-layout.md +49 -0
  11. package/docs/decisions/ADR-0005-app-provided-oauth-clients.md +54 -0
  12. package/docs/terminal-tui.md +344 -0
  13. package/package.json +11 -4
  14. package/src/accounts/accounts.test.ts +197 -1
  15. package/src/accounts/accounts.ts +266 -28
  16. package/src/cli.ts +7 -3
  17. package/src/core/bus.test.ts +22 -0
  18. package/src/core/bus.ts +17 -2
  19. package/src/harness.ts +27 -4
  20. package/src/hub/catalog.json +123 -0
  21. package/src/hub/cli.ts +59 -0
  22. package/src/hub/hub.test.ts +205 -0
  23. package/src/hub/hub.ts +256 -0
  24. package/src/hub/schema.ts +81 -0
  25. package/src/index.ts +12 -2
  26. package/src/mcp/connections.ts +39 -12
  27. package/src/mcp/service.test.ts +49 -3
  28. package/src/mcp/service.ts +14 -3
  29. package/src/mcp/types.ts +10 -0
  30. package/src/memory/api.ts +16 -2
  31. package/src/memory/blocks.ts +3 -1
  32. package/src/memory/caller.ts +13 -1
  33. package/src/memory/curation.test.ts +206 -0
  34. package/src/memory/curation.ts +64 -0
  35. package/src/memory/dispatch.ts +5 -0
  36. package/src/memory/maintenance.test.ts +17 -1
  37. package/src/memory/maintenance.ts +367 -18
  38. package/src/memory/operations.ts +12 -0
  39. package/src/memory/proposals.ts +16 -8
  40. package/src/memory/recall.test.ts +11 -0
  41. package/src/memory/recall.ts +11 -3
  42. package/src/memory/trajectory.test.ts +178 -0
  43. package/src/memory/trajectory.ts +220 -0
  44. package/src/memory/wiki.ts +2 -1
  45. package/src/memory/wikiIndex.ts +3 -2
  46. package/src/plugins/builtin.ts +4 -2
  47. package/src/plugins/catalogue.test.ts +1 -1
  48. package/src/server/methods.ts +43 -2
  49. package/src/server/server.test.ts +20 -1
  50. package/src/sessions/approvals.test.ts +49 -0
  51. package/src/sessions/approvals.ts +26 -4
  52. package/src/sessions/contracts.ts +29 -3
  53. package/src/sessions/conversation.test.ts +83 -0
  54. package/src/sessions/lineageJoin.ts +1 -1
  55. package/src/sessions/policy.ts +4 -0
  56. package/src/sessions/questionBatches.test.ts +110 -0
  57. package/src/sessions/registry.ts +145 -27
  58. package/src/sessions/runStore.ts +14 -0
  59. package/src/sessions/runner.ts +45 -4
  60. package/src/sessions/sessions.test.ts +137 -4
  61. package/src/sessions/sessions.ts +51 -15
  62. package/src/sessions/subagentService.test.ts +159 -0
  63. package/src/sessions/subagentService.ts +236 -0
  64. package/src/sessions/subagents.ts +97 -0
  65. package/src/skills/registry.ts +16 -10
  66. package/src/terminal/accountsMenu.test.ts +225 -0
  67. package/src/terminal/accountsMenu.ts +382 -0
  68. package/src/terminal/control.test.ts +23 -0
  69. package/src/terminal/control.ts +23 -0
  70. package/src/terminal/controller.ts +134 -7
  71. package/src/terminal/hubMenu.ts +24 -0
  72. package/src/terminal/launch.test.ts +5 -14
  73. package/src/terminal/launch.ts +2 -42
  74. package/src/terminal/piExtension.lifecycle.test.ts +55 -0
  75. package/src/terminal/piExtension.ts +91 -6
  76. package/src/terminal/socket.test.ts +23 -0
  77. package/src/terminal/socket.ts +55 -20
  78. package/src/terminal/standalone.test.ts +37 -0
  79. package/src/terminal/standalone.ts +28 -7
  80. package/src/terminal/terminal.test.ts +220 -16
  81. package/src/terminal/terminals.ts +234 -16
  82. package/src/terminal/trajectory.test.ts +66 -0
  83. package/src/terminal/trajectory.ts +44 -0
  84. package/src/terminal/tui/application.test.ts +290 -0
  85. package/src/terminal/tui/application.ts +653 -0
  86. package/src/terminal/tui/commands.test.ts +278 -0
  87. package/src/terminal/tui/commands.ts +443 -0
  88. package/src/terminal/tui/dialogs.ts +301 -0
  89. package/src/terminal/tui/editor.test.ts +113 -0
  90. package/src/terminal/tui/editor.ts +109 -0
  91. package/src/terminal/tui/keybindings.test.ts +30 -0
  92. package/src/terminal/tui/keybindings.ts +59 -0
  93. package/src/terminal/tui/piAdapter.ts +62 -0
  94. package/src/terminal/tui/planMode.test.ts +10 -0
  95. package/src/terminal/tui/planMode.ts +12 -0
  96. package/src/terminal/tui/presentation.test.ts +79 -0
  97. package/src/terminal/tui/questions.test.ts +41 -0
  98. package/src/terminal/tui/questions.ts +47 -0
  99. package/src/terminal/tui/runtime.socket.test.ts +178 -0
  100. package/src/terminal/tui/runtime.test.ts +225 -0
  101. package/src/terminal/tui/runtime.ts +403 -0
  102. package/src/terminal/tui/screen.test.ts +143 -0
  103. package/src/terminal/tui/screen.ts +121 -0
  104. package/src/terminal/tui/sessionUi.ts +24 -0
  105. package/src/terminal/tui/settings.test.ts +150 -0
  106. package/src/terminal/tui/settings.ts +188 -0
  107. package/src/terminal/tui/skillInvocation.test.ts +71 -0
  108. package/src/terminal/tui/skillInvocation.ts +51 -0
  109. package/src/terminal/tui/status.test.ts +48 -0
  110. package/src/terminal/tui/status.ts +82 -0
  111. package/src/terminal/tui/theme.ts +185 -0
  112. package/src/terminal/tui/tools.test.ts +145 -0
  113. package/src/terminal/tui/tools.ts +142 -0
  114. package/src/terminal/tui/trajectoryPanel.test.ts +99 -0
  115. package/src/terminal/tui/trajectoryPanel.ts +226 -0
  116. package/src/terminal/tui/transcript.test.ts +39 -0
  117. package/src/terminal/tui/transcript.ts +135 -0
  118. package/src/terminal/tui/ui.test.ts +313 -0
  119. package/src/terminal/tui/ui.ts +166 -0
  120. package/src/terminal/tui/welcome.ts +102 -0
  121. package/src/terminal/tui/workingStatus.test.ts +44 -0
  122. package/src/terminal/tui/workingStatus.ts +238 -0
  123. package/src/tools/askUser.test.ts +69 -0
  124. package/src/tools/askUser.ts +31 -17
  125. package/src/tools/definitions.ts +42 -1
  126. package/src/tools/maintenance.ts +29 -0
  127. package/src/tools/memoryTools.ts +1 -1
  128. package/src/tools/registryWrite.test.ts +101 -0
  129. package/src/tools/registryWrite.ts +182 -0
  130. package/src/tools/spawnSubagent.ts +47 -0
  131. package/src/tools/types.ts +2 -0
@@ -0,0 +1,182 @@
1
+ // Writing skills, rules, prompts and plugins directly, for the agent that wrote them. Nothing
2
+ // goes through the Inbox first, but every write is recorded there, and a plugin's code runs only
3
+ // once it is trusted. A change that would alter an item other people already use goes to the
4
+ // Inbox instead, as before.
5
+ import { join, resolve } from 'node:path'
6
+
7
+ import { invalid } from '../core/errors'
8
+ import type { Harness } from '../harness'
9
+ import { actorOf, type CallerContext } from '../memory/caller'
10
+ import { enqueueCuration } from '../memory/curation'
11
+ import { inbox } from '../memory/operations'
12
+ import { parkRegistryProposal } from '../memory/proposals'
13
+ import { looksSecret } from '../memory/secrets'
14
+ import * as store from '../memory/store'
15
+ import { reindexQuietly } from '../memory/wikiIndex'
16
+ import { attach, ensureAdopted, loadingFor, trust } from '../plugins/api'
17
+ import * as attachments from '../plugins/attachments'
18
+ import type { PluginDescriptor } from '../plugins/types'
19
+ import { acceptPluginProposal, checkPluginProposal } from '../plugins/proposal'
20
+ import * as registry from '../skills/registry'
21
+ import type { ToolProvider, ToolSpec } from './types'
22
+
23
+ export const REGISTRY_WRITE = 'registry_write'
24
+ export const PLUGIN_WRITE = 'plugin_write'
25
+
26
+ const MAX_BODY_BYTES = 64 * 1024
27
+ const text = (value: unknown): string => (typeof value === 'string' ? value : '')
28
+
29
+ /** The tools as a plugin, for an application that provides them. */
30
+ export const REGISTRY_WRITE_PLUGIN: PluginDescriptor = {
31
+ id: 'registry-write',
32
+ title: 'Skills and plugins',
33
+ description: 'Lets an agent write a skill, rule, prompt or plugin directly. A new item is on only for the agent that wrote it. A plugin is switched on for that agent and its code is trusted only after it is written; an item already in use by others goes to the Inbox.',
34
+ manage: 'tools',
35
+ tools: [
36
+ { name: REGISTRY_WRITE, description: 'Write a skill, rule or prompt' },
37
+ { name: PLUGIN_WRITE, description: 'Write a plugin' }
38
+ ]
39
+ }
40
+
41
+ export interface RegistryToolOptions {
42
+ harness: Harness
43
+ }
44
+
45
+ /** The `registry_write` and `plugin_write` tools. Only the names a session allows are registered. */
46
+ export function registryTools(options: RegistryToolOptions): ToolProvider {
47
+ return ({ caller }) => [registryWriteTool(options.harness, caller), pluginWriteTool(options.harness, caller)]
48
+ }
49
+
50
+ function actorLabel(caller: CallerContext): string {
51
+ return caller.agentName ? `${caller.agentName} (${actorOf(caller)})` : actorOf(caller)
52
+ }
53
+
54
+ function requireAgent(caller: CallerContext): string {
55
+ if (!caller.agentId) throw invalid('Only an agent can write skills, rules, prompts, or plugins.')
56
+ return caller.agentId
57
+ }
58
+
59
+ /**
60
+ * Whether an existing item belongs to this agent alone: switched on for no one else, nowhere
61
+ * wider, and not built in. Anything else is someone else's to review.
62
+ */
63
+ function ownedByCaller(choices: attachments.Attachments, id: string, agentId: string, builtin: boolean): boolean {
64
+ const where = attachments.describe(choices, id, builtin)
65
+ if (where.global || where.on.projectIds.length) return false
66
+ return where.on.agentIds.length === 1 && where.on.agentIds[0] === agentId
67
+ }
68
+
69
+ function registryWriteTool(harness: Harness, caller: CallerContext): ToolSpec {
70
+ return {
71
+ name: REGISTRY_WRITE,
72
+ label: caller.vaultAccess ? 'Propose a skill, rule or prompt' : 'Write a skill, rule or prompt',
73
+ description: caller.vaultAccess ? 'Submit a bounded text skill, rule or prompt for curator review. It stays inactive until reviewed; permissions and code trust remain unchanged.' :
74
+ 'Write a skill, rule or prompt directly. It is on only for you until the user switches it on for others. ' +
75
+ 'An item that others already use, or that is built in, is not changed: your text goes to the Inbox for the user to review. ' +
76
+ 'A rule reaches every future prompt of the agents it is on for, so write one only when it should always apply.',
77
+ parameters: (Type) =>
78
+ Type.Object({
79
+ kind: Type.String({ description: 'skill, prompt, or rule' }),
80
+ name: Type.String({ description: 'A short name, such as release-notes' }),
81
+ description: Type.String({ description: 'One line the user reads first' }),
82
+ body: Type.String({ description: 'The text itself, as Markdown' }),
83
+ reason: Type.Optional(Type.String({ description: 'Why you are writing it' }))
84
+ }),
85
+ execute: async (input) => {
86
+ const agentId = requireAgent(caller)
87
+ const kind = text(input.kind)
88
+ const name = text(input.name).trim()
89
+ const description = text(input.description).trim()
90
+ const body = text(input.body)
91
+ const reason = text(input.reason).trim()
92
+ if (!['skill', 'prompt', 'rule'].includes(kind)) throw invalid('kind must be skill, prompt, or rule.')
93
+ if (!name || !body.trim()) throw invalid('A skill, prompt, or rule needs a name and a body.')
94
+ if (Buffer.byteLength(body, 'utf8') > MAX_BODY_BYTES) throw invalid('The body is larger than 64 KiB.')
95
+ if (looksSecret(body)) throw invalid('The text looks like a credential, so it was not saved.')
96
+
97
+ if (caller.vaultAccess === 'self' || caller.vaultAccess === 'propose' || caller.vaultAccess === 'curator') {
98
+ const job = enqueueCuration(harness.env.root, { kind: 'registry', proposal: { kind, name, description, body, reason }, caller })
99
+ harness.bus.emit({ type: 'wiki.changed' })
100
+ return `Submitted proposal ${job.id} for curator review. Nothing has been activated.`
101
+ }
102
+
103
+ const { root } = harness.env
104
+ const wiki = store.wikiDir(root)
105
+ const id = `${kind}s/${store.slug(name)}`
106
+ const existing = registry.list(root).find((item) => item.id === id)
107
+ const choices = attachments.load(root)
108
+ if (existing && !ownedByCaller(choices, id, agentId, !!existing.builtin)) {
109
+ const parked = parkRegistryProposal(wiki, { kind: 'agent', runId: caller.runId ?? null, actor: actorLabel(caller) }, { kind, name, description, body, reason })
110
+ harness.bus.emit({ type: 'wiki.changed' })
111
+ return `The ${kind} change (${parked}) is in the Wiki Inbox: "${id}" is already used by others, so the user reviews it before it changes.`
112
+ }
113
+
114
+ registry.writeItem(root, kind, name, description, body, reason || `Written by ${actorLabel(caller)}`, actorLabel(caller))
115
+ attachments.set(choices, [id], { agentId }, true, false)
116
+ attachments.save(root, choices)
117
+ reindexQuietly(root)
118
+ harness.bus.emit({ type: 'plugins.changed' })
119
+ inbox(wiki, 'applied', `Wrote ${kind} "${name}"`, `${reason || 'Written by an agent.'}\n\nBy ${actorLabel(caller)}. It is on only for that agent.`, [], null)
120
+ return `Saved the ${kind} "${id}". It is on for you only; the user can switch it on for everyone.`
121
+ }
122
+ }
123
+ }
124
+
125
+ function pluginWriteTool(harness: Harness, caller: CallerContext): ToolSpec {
126
+ return {
127
+ name: PLUGIN_WRITE,
128
+ label: caller.vaultAccess ? 'Propose a plugin' : 'Write a plugin',
129
+ description: caller.vaultAccess ? 'Submit a plugin bundle for curator and user review. It remains inactive and untrusted; executable code requires an explicit user trust decision. Include at most 40 bounded files; never include credentials.' :
130
+ 'Write a plugin directly: a bundle of files that changes how agents work. It is switched on for you only. ' +
131
+ 'If it contains code (extensions/ or hooks.mjs), that code is trusted and runs in your sessions; nobody else runs it. ' +
132
+ 'Files by folder: skills/<name>/SKILL.md, prompts/<name>.md, extensions/<name>.ts, and hooks.mjs. Do not include package.json. Put no key or password in a file.',
133
+ parameters: (Type) =>
134
+ Type.Object({
135
+ name: Type.String({ description: 'A short name, such as memory-to-docs' }),
136
+ description: Type.String({ description: 'One line the user reads first' }),
137
+ extends: Type.Optional(Type.Array(Type.String({ description: 'memory, wiki, or history' }))),
138
+ reason: Type.Optional(Type.String({ description: 'Why you are writing it' })),
139
+ files: Type.Array(Type.Object({ path: Type.String({ description: 'A path inside the plugin' }), content: Type.String() }), { maxItems: 40 })
140
+ }),
141
+ execute: async (input) => {
142
+ const agentId = requireAgent(caller)
143
+ const files = (Array.isArray(input.files) ? input.files : []).map((file) => ({ path: text((file as { path?: unknown }).path), content: text((file as { content?: unknown }).content) }))
144
+ const proposal = {
145
+ name: text(input.name),
146
+ description: text(input.description),
147
+ extends: (Array.isArray(input.extends) ? input.extends : []).filter((part): part is string => typeof part === 'string'),
148
+ reason: text(input.reason),
149
+ files
150
+ }
151
+ const checked = checkPluginProposal(proposal)
152
+ if (caller.vaultAccess === 'self' || caller.vaultAccess === 'propose' || caller.vaultAccess === 'curator') {
153
+ const job = enqueueCuration(harness.env.root, { kind: 'plugin', proposal, caller })
154
+ harness.bus.emit({ type: 'wiki.changed' })
155
+ return `Submitted proposal ${job.id}. Executable code requires user review and trust.`
156
+ }
157
+ const { root } = harness.env
158
+ // Trust the packages that were there first, so the new one is not adopted with them.
159
+ await ensureAdopted(harness)
160
+ acceptPluginProposal(root, proposal)
161
+
162
+ let note = ''
163
+ try {
164
+ if (checked.runsCode) {
165
+ const loading = await loadingFor(harness, { agentId })
166
+ const folder = resolve(join(root, 'plugins', checked.slug))
167
+ const found = Object.entries(loading?.packageCode ?? {}).find(([dir]) => resolve(dir) === folder)
168
+ if (!found) throw new Error('its code was not found after it was saved')
169
+ await trust(harness, { agentId, hash: found[1].hash })
170
+ }
171
+ await attach(harness, { id: `package:${checked.slug}`, scope: { agentId } }, true)
172
+ } catch (error) {
173
+ note = ` It is saved but not switched on: ${error instanceof Error ? error.message : String(error)}. The user can switch it on in Plugins.`
174
+ }
175
+ harness.bus.emit({ type: 'plugins.changed' })
176
+ inbox(store.wikiDir(root), 'applied', `Wrote plugin "${checked.slug}"`, `${proposal.reason || 'Written by an agent.'}\n\nBy ${actorLabel(caller)}.${checked.runsCode ? ' Its code runs only for that agent.' : ''}`, [], null)
177
+ return note
178
+ ? `The plugin "${checked.slug}" was written.${note}`
179
+ : `The plugin "${checked.slug}" was written and is on for you only.${checked.runsCode ? ' Its code is trusted for your sessions.' : ''}`
180
+ }
181
+ }
182
+ }
@@ -0,0 +1,47 @@
1
+ import { HarnessError, invalid } from '../core/errors'
2
+ import type { Subagents } from '../sessions/subagentService'
3
+ import { SPAWN_SUBAGENT, WAIT_SUBAGENTS, SUBAGENT_RECEIPT, type SubagentReceipt, type SubagentResult } from '../sessions/subagents'
4
+ import type { ToolResult, ToolSpec } from './types'
5
+
6
+ export { SPAWN_SUBAGENT, SUBAGENT_RELATION, DEFAULT_SUBAGENT_DEPTH, MAX_SUBAGENT_DEPTH, subagentDepth, subagentReport, type SubagentOptions } from '../sessions/subagents'
7
+
8
+ function reported(parentRunId: string, results: SubagentResult[], spawned?: string[]): ToolResult {
9
+ const included: SubagentResult[] = []
10
+ let length = 0
11
+ for (const result of results) {
12
+ if (length + result.text.length > 24_000 && included.length) break
13
+ included.push(result)
14
+ length += result.text.length + 300
15
+ }
16
+ const receipt: SubagentReceipt = { version: 1, ownerRunId: parentRunId, ...(spawned ? { spawned } : {}), delivered: included.map((result) => result.runId) }
17
+ return { text: JSON.stringify({ results: included, ...(results.length > included.length ? { remaining: results.slice(included.length).map((result) => result.runId) } : {}) }), details: { [SUBAGENT_RECEIPT]: receipt } }
18
+ }
19
+
20
+ export function subagentTools(service: Subagents, parentRunId: string): ToolSpec[] {
21
+ const execute = (fn: (input: Record<string, unknown>) => Promise<ToolResult>): ToolSpec['execute'] => async (input) => {
22
+ try { return await fn(input) } catch (error) {
23
+ if (error instanceof HarnessError) return error.message
24
+ throw error
25
+ }
26
+ }
27
+ return [{
28
+ name: SPAWN_SUBAGENT,
29
+ label: 'Start a subagent',
30
+ description: 'Start a fresh child run of yourself for independent work. Give a complete brief: the child has no conversation history and no more capabilities than you. Returns its run ID immediately by default so you can continue working. Results arrive automatically before you finish. Use wait_subagents to join selected children, or wait: true for an inline result. Stopping you stops your children.',
31
+ parameters: (Type) => Type.Object({ brief: Type.String(), tools: Type.Optional(Type.Array(Type.String())), wait: Type.Optional(Type.Boolean({ description: 'Wait for the child and return its result; default false' })) }),
32
+ execute: execute(async (input) => {
33
+ const child = await service.spawn({ parentRunId, brief: input.brief as string, tools: input.tools as string[] | undefined, wait: input.wait as boolean | undefined })
34
+ if (input.wait === true) return reported(parentRunId, service.results({ parentRunId, runIds: [child.runId] }), [child.runId])
35
+ return { text: JSON.stringify(child), details: { [SUBAGENT_RECEIPT]: { version: 1, ownerRunId: parentRunId, spawned: [child.runId] } satisfies SubagentReceipt } }
36
+ })
37
+ }, {
38
+ name: WAIT_SUBAGENTS,
39
+ label: 'Wait for subagents',
40
+ description: 'Wait for all selected direct subagents to settle and return their results, including failures. Omit runIds to select your current children. Do useful independent work before waiting; results also arrive automatically before your final reply.',
41
+ parameters: (Type) => Type.Object({ runIds: Type.Optional(Type.Array(Type.String())) }),
42
+ execute: execute(async (input) => {
43
+ if (input.runIds !== undefined && !Array.isArray(input.runIds)) throw invalid('runIds must be an array of child run IDs.')
44
+ return reported(parentRunId, await service.wait({ parentRunId, runIds: input.runIds as string[] | undefined }))
45
+ })
46
+ }]
47
+ }
@@ -7,6 +7,8 @@ import type { ToolAttachmentRef } from '../sessions/contracts'
7
7
 
8
8
  export interface ToolResult {
9
9
  text: string
10
+ /** Native-history metadata; never interpreted as model instructions. */
11
+ details?: Record<string, unknown>
10
12
  image?: { data: string; mimeType: string }
11
13
  /** References to content stored by the provider; bytes never enter the run-event stream. */
12
14
  attachments?: ToolAttachmentRef[]