@xingular/harness 0.0.0-stage → 0.1.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 (133) hide show
  1. package/README.md +269 -2
  2. package/dist/cli.js +11046 -0
  3. package/dist/terminal-pi.js +326 -0
  4. package/package.json +41 -4
  5. package/src/accounts/accounts.test.ts +223 -0
  6. package/src/accounts/accounts.ts +522 -0
  7. package/src/accounts/env.ts +204 -0
  8. package/src/accounts/secrets.ts +50 -0
  9. package/src/accounts/store.ts +338 -0
  10. package/src/capabilities/api.ts +75 -0
  11. package/src/capabilities/runSnapshot.ts +59 -0
  12. package/src/capabilities/types.ts +34 -0
  13. package/src/cli.ts +110 -0
  14. package/src/core/bus.ts +34 -0
  15. package/src/core/changes.ts +33 -0
  16. package/src/core/env.ts +27 -0
  17. package/src/core/errors.ts +32 -0
  18. package/src/core/frontmatter.ts +47 -0
  19. package/src/core/fs.test.ts +38 -0
  20. package/src/core/fs.ts +92 -0
  21. package/src/core/index.ts +193 -0
  22. package/src/core/path.ts +45 -0
  23. package/src/core/projects.ts +90 -0
  24. package/src/core/text.ts +39 -0
  25. package/src/harness.ts +289 -0
  26. package/src/index.ts +69 -0
  27. package/src/mcp/connections.ts +441 -0
  28. package/src/mcp/manager.ts +130 -0
  29. package/src/mcp/oauth.ts +195 -0
  30. package/src/mcp/service.test.ts +376 -0
  31. package/src/mcp/service.ts +567 -0
  32. package/src/mcp/types.ts +105 -0
  33. package/src/memory/api.test.ts +82 -0
  34. package/src/memory/api.ts +287 -0
  35. package/src/memory/blocks.test.ts +78 -0
  36. package/src/memory/blocks.ts +406 -0
  37. package/src/memory/caller.ts +57 -0
  38. package/src/memory/dispatch.ts +59 -0
  39. package/src/memory/facts.test.ts +41 -0
  40. package/src/memory/facts.ts +248 -0
  41. package/src/memory/graph.ts +103 -0
  42. package/src/memory/health.test.ts +130 -0
  43. package/src/memory/health.ts +74 -0
  44. package/src/memory/maintainer.ts +272 -0
  45. package/src/memory/maintenance.test.ts +176 -0
  46. package/src/memory/maintenance.ts +330 -0
  47. package/src/memory/migrate.ts +79 -0
  48. package/src/memory/operations.ts +138 -0
  49. package/src/memory/proposals.test.ts +168 -0
  50. package/src/memory/proposals.ts +576 -0
  51. package/src/memory/recall.test.ts +104 -0
  52. package/src/memory/recall.ts +271 -0
  53. package/src/memory/references.ts +77 -0
  54. package/src/memory/runContext.ts +93 -0
  55. package/src/memory/secrets.ts +6 -0
  56. package/src/memory/store.test.ts +66 -0
  57. package/src/memory/store.ts +385 -0
  58. package/src/memory/wiki.test.ts +47 -0
  59. package/src/memory/wiki.ts +422 -0
  60. package/src/memory/wikiIndex.test.ts +88 -0
  61. package/src/memory/wikiIndex.ts +116 -0
  62. package/src/plugins/api.ts +181 -0
  63. package/src/plugins/attachments.test.ts +84 -0
  64. package/src/plugins/attachments.ts +128 -0
  65. package/src/plugins/builtin.ts +82 -0
  66. package/src/plugins/catalogue.test.ts +254 -0
  67. package/src/plugins/catalogue.ts +250 -0
  68. package/src/plugins/cli.ts +184 -0
  69. package/src/plugins/discover.ts +151 -0
  70. package/src/plugins/firstParty.test.ts +143 -0
  71. package/src/plugins/firstParty.ts +129 -0
  72. package/src/plugins/hooks.test.ts +250 -0
  73. package/src/plugins/hooks.ts +239 -0
  74. package/src/plugins/identity.ts +37 -0
  75. package/src/plugins/install.test.ts +107 -0
  76. package/src/plugins/install.ts +106 -0
  77. package/src/plugins/inventory.ts +123 -0
  78. package/src/plugins/manifest.ts +44 -0
  79. package/src/plugins/plugins.test.ts +205 -0
  80. package/src/plugins/plugins.ts +184 -0
  81. package/src/plugins/proposal.ts +121 -0
  82. package/src/plugins/runtime.test.ts +40 -0
  83. package/src/plugins/runtime.ts +82 -0
  84. package/src/plugins/trust.ts +142 -0
  85. package/src/plugins/types.ts +130 -0
  86. package/src/prompt/compile.test.ts +261 -0
  87. package/src/prompt/compile.ts +732 -0
  88. package/src/server/methods.ts +308 -0
  89. package/src/server/remote.ts +77 -0
  90. package/src/server/rpc.ts +116 -0
  91. package/src/server/serve.ts +28 -0
  92. package/src/server/server.test.ts +174 -0
  93. package/src/sessions/approvals.ts +118 -0
  94. package/src/sessions/contracts.ts +299 -0
  95. package/src/sessions/conversation.test.ts +150 -0
  96. package/src/sessions/extensionSession.test.ts +74 -0
  97. package/src/sessions/extensionUi.test.ts +65 -0
  98. package/src/sessions/extensionUi.ts +102 -0
  99. package/src/sessions/history.ts +51 -0
  100. package/src/sessions/lineageJoin.ts +75 -0
  101. package/src/sessions/policy.ts +32 -0
  102. package/src/sessions/pricing.ts +60 -0
  103. package/src/sessions/reasoningSummaries.ts +59 -0
  104. package/src/sessions/registry.ts +294 -0
  105. package/src/sessions/runIndex.ts +99 -0
  106. package/src/sessions/runStore.test.ts +152 -0
  107. package/src/sessions/runStore.ts +332 -0
  108. package/src/sessions/runner.ts +556 -0
  109. package/src/sessions/runtimeResources.test.ts +61 -0
  110. package/src/sessions/sessions.test.ts +434 -0
  111. package/src/sessions/sessions.ts +295 -0
  112. package/src/skills/registry.test.ts +104 -0
  113. package/src/skills/registry.ts +394 -0
  114. package/src/terminal/cli.ts +149 -0
  115. package/src/terminal/client.ts +74 -0
  116. package/src/terminal/controller.ts +227 -0
  117. package/src/terminal/piExtension.ts +208 -0
  118. package/src/terminal/pluginControl.test.ts +146 -0
  119. package/src/terminal/pluginMenu.ts +112 -0
  120. package/src/terminal/socket.ts +182 -0
  121. package/src/terminal/standalone.test.ts +115 -0
  122. package/src/terminal/standalone.ts +126 -0
  123. package/src/terminal/terminal.test.ts +302 -0
  124. package/src/terminal/terminals.ts +429 -0
  125. package/src/tools/askUser.ts +45 -0
  126. package/src/tools/definitions.ts +187 -0
  127. package/src/tools/memoryTools.ts +22 -0
  128. package/src/tools/pluginPropose.ts +41 -0
  129. package/src/tools/types.ts +36 -0
  130. package/src/web/safeRequest.ts +171 -0
  131. package/src/web/text.ts +53 -0
  132. package/src/web/tools.ts +134 -0
  133. package/src/web/web.test.ts +141 -0
@@ -0,0 +1,174 @@
1
+ import { mkdtempSync } from 'node:fs'
2
+ import { tmpdir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import { afterEach, describe, expect, it } from 'vitest'
5
+
6
+ import { memorySecretStore } from '../accounts/secrets'
7
+ import { createHarness, type Harness } from '../harness'
8
+ import type { PiSessionLike } from '../sessions/runner'
9
+ import { rootWithProject, writeFile } from '../../tests/helpers'
10
+ import { remoteDirectory, remotePolicy, remoteSecrets, remoteTools } from './remote'
11
+ import { RpcPeer, type Transport } from './rpc'
12
+ import { attach, serve } from './serve'
13
+
14
+ const open: Harness[] = []
15
+ afterEach(async () => {
16
+ for (const harness of open.splice(0)) await harness.close()
17
+ })
18
+
19
+ /** A host on the other end of the protocol: sends requests, answers the harness's calls. */
20
+ function host(hostCalls: Record<string, (params: any) => unknown> = {}) {
21
+ let toHarness: (line: string) => void = () => undefined
22
+ const events: any[] = []
23
+ const notices: any[] = []
24
+ const waiting = new Map<string, { resolve: (value: any) => void; reject: (error: any) => void }>()
25
+ let next = 0
26
+ const transport: Transport = {
27
+ onLine: (listener) => void (toHarness = listener),
28
+ write: (line) => {
29
+ const message = JSON.parse(line)
30
+ if (message.event) events.push(message.event)
31
+ else if (message.notice) notices.push(message.notice)
32
+ else if (message.call) {
33
+ queueMicrotask(async () => {
34
+ try {
35
+ const handler = hostCalls[message.call]
36
+ if (!handler) throw new Error(`host has no ${message.call}`)
37
+ toHarness(JSON.stringify({ v: 1, id: message.id, result: (await handler(message.params)) ?? null }))
38
+ } catch (error) {
39
+ toHarness(JSON.stringify({ v: 1, id: message.id, error: { code: 'host_error', message: error instanceof Error ? error.message : String(error) } }))
40
+ }
41
+ })
42
+ } else {
43
+ const pending = waiting.get(message.id)
44
+ waiting.delete(message.id)
45
+ if (message.error) pending?.reject(message.error)
46
+ else pending?.resolve(message.result)
47
+ }
48
+ }
49
+ }
50
+ const request = <T = any>(method: string, params: unknown = {}): Promise<T> =>
51
+ new Promise<T>((resolve, reject) => {
52
+ const id = `h${++next}`
53
+ waiting.set(id, { resolve, reject })
54
+ toHarness(JSON.stringify({ v: 1, id, method, params }))
55
+ })
56
+ return { transport, request, events, notices }
57
+ }
58
+
59
+ const idle = (): PiSessionLike => ({ sessionId: 'native-1', subscribe: () => () => undefined, prompt: async () => undefined, sendCustomMessage: async () => undefined, abort: async () => undefined, dispose: () => undefined })
60
+
61
+ describe('the harness served to a host', () => {
62
+ it('answers by method name, reports failures with their code, and forwards events and notices', async () => {
63
+ const { transport, request, events, notices } = host()
64
+ const harness = createHarness({ dataRoot: rootWithProject(), stateDir: mkdtempSync(join(tmpdir(), 'hs-')), secrets: memorySecretStore(), sessionFactory: async () => idle() })
65
+ open.push(harness)
66
+ serve(harness, transport)
67
+
68
+ const status = await request('harness.status')
69
+ expect(status).toMatchObject({ dataRoot: harness.env.root, productName: 'Xingular Harness', activeRuns: [] })
70
+ expect(await request<string[]>('harness.methods')).toEqual(expect.arrayContaining(['accounts.list', 'sessions.run', 'wiki.pages', 'terminal.prepare', 'skills.list', 'skills.import', 'connections.list', 'harness.shutdown']))
71
+
72
+ const overview = await request('accounts.create', { label: 'Main', authKind: 'apiKey' })
73
+ expect(overview.accounts).toHaveLength(1)
74
+ expect(notices).toContainEqual(expect.objectContaining({ type: 'accounts.changed' }))
75
+ await expect(request('accounts.rename', { accountId: 'nope', label: 'x' })).rejects.toMatchObject({ code: 'not_found' })
76
+ await expect(request('accounts.rename', {})).rejects.toMatchObject({ code: 'invalid_request', message: 'accountId is required.' })
77
+ await expect(request('nope.nothing')).rejects.toMatchObject({ code: 'unknown_method' })
78
+
79
+ expect((await request<any[]>('wiki.namespaces')).map((entry) => entry.namespace)).toEqual(expect.arrayContaining(['/projects/app']))
80
+ const blocks = await request<any[]>('blocks.list', { agentIds: ['a1'] })
81
+ expect(blocks.map((block) => block.label)).toEqual(expect.arrayContaining(['user', 'persona', 'notes']))
82
+ expect(await request('memory.call', { context: { agentId: 'a1', agentName: 'Helper', actor: 'Chat' }, call: 'memory.append', params: { block: 'notes', text: 'Ship on Fridays.' } })).toContain('notes')
83
+ expect(notices).toContainEqual({ type: 'wiki.changed' })
84
+ const compiled = await request('context.compile', { context: { agentId: 'a1', agentName: 'Helper', actor: 'Chat' }, render: true })
85
+ expect(compiled.text).toContain('Ship on Fridays.')
86
+ expect(await request('context.profiles')).toEqual({ profiles: {}, stats: [] })
87
+
88
+ const started = await request('sessions.run', { run: { id: 'r1', sessionId: 'a1' }, cwd: harness.env.root, sessionDir: join(harness.env.root, 'sessions', 'a1'), text: 'hello', caller: { agentId: 'a1', agentName: 'Helper', actor: 'Chat' }, tools: { allow: ['read'] } })
89
+ expect(started).toEqual({ runId: 'r1', nativeSessionId: 'native-1' })
90
+ await new Promise((resolve) => setTimeout(resolve, 30))
91
+ expect(events.map((event) => event.type)).toEqual(['started', 'status.changed', 'context.snapshot', 'completed'])
92
+ expect((await request('runs.load', { runId: 'r1' })).run).toMatchObject({ id: 'r1', status: 'completed' })
93
+ expect((await request<any[]>('runs.list', { filter: { sessionId: 'a1' } })).map((run) => run.id)).toEqual(['r1'])
94
+ expect((await request('context.profiles')).stats).toMatchObject([{ subject: 'a1', mode: 'chat', contextProfile: 'full', runs: 1, completed: 1, runIds: ['r1'] }])
95
+ })
96
+
97
+ it('lets a host that is not a Node program supply secrets, policy, names, and tools over the protocol', async () => {
98
+ const secrets = new Map<string, string>()
99
+ const called: any[] = []
100
+ const { transport, request } = host({
101
+ 'secrets.get': ({ key }) => secrets.get(key) ?? null,
102
+ 'secrets.set': ({ key, value }) => void secrets.set(key, value),
103
+ 'secrets.delete': ({ key }) => void secrets.delete(key),
104
+ 'policy.scope': ({ tool }) => ({ allowed: tool !== 'bash', reason: 'No shell here.' }),
105
+ 'policy.authorize': () => null,
106
+ 'tools.call': (params) => {
107
+ called.push(params)
108
+ return { ok: true, echoed: params.input }
109
+ }
110
+ })
111
+ const peer = new RpcPeer(transport)
112
+ let gate: { check: (name: string, input: unknown) => Promise<string | null> } | null = null
113
+ let offered: { name: string; execute: (input: Record<string, unknown>) => Promise<unknown> }[] = []
114
+ const harness = createHarness({
115
+ dataRoot: rootWithProject(),
116
+ stateDir: mkdtempSync(join(tmpdir(), 'hs-')),
117
+ secrets: remoteSecrets(peer),
118
+ policy: remotePolicy(peer),
119
+ directory: remoteDirectory(peer),
120
+ sessionFactory: async (input) => {
121
+ gate = input.gate
122
+ offered = input.tools.filter((tool) => input.allow.includes(tool.name))
123
+ return idle()
124
+ }
125
+ })
126
+ open.push(harness)
127
+ harness.sessions.provide(remoteTools(peer))
128
+ attach(harness, peer)
129
+
130
+ const { accounts } = await request('accounts.create', { label: 'Main', authKind: 'apiKey' })
131
+ await request('accounts.setApiKey', { accountId: accounts[0].id, key: 'sk-test-0000000000000000', provider: 'anthropic' })
132
+ expect([...secrets.keys()]).toEqual([`${accounts[0].id}/pi-auth/anthropic`])
133
+
134
+ await request('directory.set', { agents: { a1: 'Scout' } })
135
+ expect(harness.env.directory.agentName('a1')).toBe('Scout')
136
+
137
+ expect(await request('tools.register', { tools: [{ name: 'lookup', description: 'Look something up', parameters: { type: 'object', properties: { q: { type: 'string' } } } }] })).toEqual({ registered: ['lookup'] })
138
+ await request('sessions.run', { run: { id: 'r1', sessionId: 'a1' }, cwd: harness.env.root, sessionDir: join(harness.env.root, 'sessions', 'a1'), text: 'hello', caller: { agentId: 'a1', actor: 'Chat' }, tools: { allow: ['lookup', 'bash'] } })
139
+ expect(offered.map((tool) => tool.name)).toContain('lookup')
140
+ expect(await offered.find((tool) => tool.name === 'lookup')!.execute({ q: 'x' })).toBe('{"ok":true,"echoed":{"q":"x"}}')
141
+ expect(called[0]).toMatchObject({ name: 'lookup', runId: 'r1', sessionId: 'a1', caller: { agentId: 'a1' } })
142
+ expect(await gate!.check('bash', {})).toBe('No shell here.')
143
+ expect(await gate!.check('lookup', {})).toBeNull()
144
+ })
145
+ })
146
+
147
+ describe('built-in skills', () => {
148
+ it('are on everywhere until switched off, and a person\'s own item of the same name replaces one', async () => {
149
+ const builtins = mkdtempSync(join(tmpdir(), 'builtin-'))
150
+ writeFile(join(builtins, 'skills', 'review', 'SKILL.md'), '---\nname: review\ndescription: Review a change before it ships\n---\nRead the diff first.\n')
151
+ writeFile(join(builtins, 'rules', 'plain.md'), '---\nname: Plain words\ndescription: Write plainly\n---\nUse plain words.\n')
152
+ const { transport, request } = host()
153
+ const harness = createHarness({ dataRoot: rootWithProject(), stateDir: mkdtempSync(join(tmpdir(), 'hs-')), secrets: memorySecretStore(), builtins: [builtins] })
154
+ open.push(harness)
155
+ serve(harness, transport)
156
+
157
+ const state = await request('skills.list')
158
+ expect(state.items).toMatchObject([{ id: 'rules/plain', builtin: true }, { id: 'skills/review', builtin: true }])
159
+ expect(state.enabled.global).toEqual(['rules/plain', 'skills/review'])
160
+ expect((await request<any[]>('skills.enabledFor', { projectId: 'p1' })).map((item) => item.id)).toEqual(['rules/plain', 'skills/review'])
161
+ expect((await request('context.compile', { context: { projectId: 'p1', actor: 'Code' }, render: true })).text).toContain('Use plain words.')
162
+
163
+ const off = await request('skills.setEnabled', { projectId: null, ids: ['skills/review'] })
164
+ expect(off.enabled).toMatchObject({ global: ['skills/review'], builtinOff: ['rules/plain'] })
165
+ expect((await request<any[]>('skills.enabledFor', {})).map((item) => item.id)).toEqual(['skills/review'])
166
+
167
+ writeFile(join(harness.env.root, 'registry', 'skills', 'review', 'SKILL.md'), '---\nname: review\ndescription: My own review steps\n---\nMine.\n')
168
+ const mine = (await request('skills.list')).items.find((item: any) => item.id === 'skills/review')
169
+ expect(mine).toMatchObject({ description: 'My own review steps' })
170
+ expect(mine.builtin).toBeUndefined()
171
+ // A person's own item is enabled the usual way, not by default.
172
+ expect((await request<any[]>('skills.enabledFor', {})).map((item) => item.id)).toEqual([])
173
+ })
174
+ })
@@ -0,0 +1,118 @@
1
+ // What the user has chosen to stop being asked about: an "always approve" switch per kind of
2
+ // session and, per session, the tools they answered "Always allow" for.
3
+ import { chmodSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+
6
+ import type { Bus } from '../core/bus'
7
+ import { invalid } from '../core/errors'
8
+ import { readJson, writeJson } from '../core/fs'
9
+ import type { RunRecord } from './contracts'
10
+
11
+ /** Kinds of session with a switch: an agent's own conversations, and sessions in a project. */
12
+ export const APPROVAL_KEYS = ['chat', 'pi'] as const
13
+
14
+ export interface ApprovalPolicy {
15
+ /** Switch key → every approval is granted without asking. */
16
+ auto: Record<string, boolean>
17
+ /** Session id → approval targets always allowed there. */
18
+ remembered: Record<string, string[]>
19
+ }
20
+
21
+ /** Why a request is granted without asking. */
22
+ export type AutomaticReason = 'always' | 'remembered' | 'scope'
23
+
24
+ /** What only the embedding application knows about a pending approval. */
25
+ export interface ApprovalFacts {
26
+ /** Unattended work keeps to its saved scope whatever the switches say. */
27
+ unattended?: boolean
28
+ /** The session may not change anything; the switch must not approve its way out of that. */
29
+ readOnly?: boolean
30
+ /** The application's own scope already covers this exact operation. */
31
+ inScope?: boolean
32
+ }
33
+
34
+ /** Why the standing choices grant this request, if they do. */
35
+ export function decide(policy: ApprovalPolicy, key: string, sessionId: string, target: string): AutomaticReason | null {
36
+ if (policy.auto[key]) return 'always'
37
+ return policy.remembered[sessionId]?.includes(target) ? 'remembered' : null
38
+ }
39
+
40
+ export function grant(policy: ApprovalPolicy, key: string, sessionId: string, target: string, facts: ApprovalFacts = {}): AutomaticReason | null {
41
+ if (facts.unattended) return null
42
+ // "Always approve" must not let a read-only session approve its way out of read-only mode.
43
+ return decide(facts.readOnly ? { auto: {}, remembered: policy.remembered } : policy, key, sessionId, target)
44
+ }
45
+
46
+ /** A conversation's runs share one switch whatever model they use; other runs follow their own. */
47
+ export const approvalKey = (run: Pick<RunRecord, 'mode' | 'harness'>): string => (run.mode === 'chat' ? 'chat' : run.harness)
48
+
49
+ export class Approvals {
50
+ private readonly path: string
51
+
52
+ constructor(stateDir: string, private readonly bus: Bus) {
53
+ this.path = join(stateDir, 'approvals.json')
54
+ }
55
+
56
+ read(): ApprovalPolicy {
57
+ const stored = readJson<Partial<ApprovalPolicy>>(this.path) ?? {}
58
+ return { auto: stored.auto ?? {}, remembered: stored.remembered ?? {} }
59
+ }
60
+
61
+ private change(update: (policy: ApprovalPolicy) => void): ApprovalPolicy {
62
+ const policy = this.read()
63
+ update(policy)
64
+ writeJson(this.path, policy)
65
+ try {
66
+ chmodSync(this.path, 0o600)
67
+ } catch {
68
+ // The file was written; a mode that cannot be set is not worth failing the change.
69
+ }
70
+ this.bus.emit({ type: 'approvals.changed' })
71
+ return policy
72
+ }
73
+
74
+ isAuto(key: string): boolean {
75
+ try {
76
+ return Boolean(this.read().auto[key])
77
+ } catch {
78
+ return false
79
+ }
80
+ }
81
+
82
+ /** Why this run's approval for `target` can be granted without asking, if it can. */
83
+ automatic(run: RunRecord, target: string, facts: ApprovalFacts = {}): AutomaticReason | null {
84
+ // What the application's own scope already covers needs neither the switch nor the user.
85
+ return grant(this.read(), approvalKey(run), run.sessionId, target, facts) ?? (!facts.unattended && facts.inScope ? 'scope' : null)
86
+ }
87
+
88
+ setAuto(key: string, on: boolean): ApprovalPolicy {
89
+ if (!(APPROVAL_KEYS as readonly string[]).includes(key)) throw invalid('Unknown harness.')
90
+ return this.change((policy) => void (policy.auto[key] = on))
91
+ }
92
+
93
+ /** Always allow `target` in this session. */
94
+ remember(sessionId: string, target: string): ApprovalPolicy {
95
+ if (!target.trim()) throw invalid('A tool is required.')
96
+ return this.change((policy) => {
97
+ const targets = (policy.remembered[sessionId] ??= [])
98
+ if (!targets.includes(target)) targets.push(target)
99
+ })
100
+ }
101
+
102
+ forget(sessionId: string, target: string): ApprovalPolicy {
103
+ return this.change((policy) => {
104
+ const targets = policy.remembered[sessionId]?.filter((item) => item !== target) ?? []
105
+ if (targets.length) policy.remembered[sessionId] = targets
106
+ else delete policy.remembered[sessionId]
107
+ })
108
+ }
109
+
110
+ /** Forgets what was remembered for a session that no longer exists. */
111
+ forgetSession(sessionId: string): void {
112
+ try {
113
+ if (sessionId in this.read().remembered) this.change((policy) => void delete policy.remembered[sessionId])
114
+ } catch {
115
+ // Nothing recorded.
116
+ }
117
+ }
118
+ }
@@ -0,0 +1,299 @@
1
+ // Run records and the run-event stream: the one contract every session shares. Every event is
2
+ // validated against these schemas before it is persisted or handed to a listener.
3
+ import { z } from 'zod'
4
+
5
+ export const runStatusSchema = z.enum(['queued', 'running', 'waiting_for_approval', 'waiting_for_input', 'interrupted', 'completed', 'failed'])
6
+ export type RunStatus = z.infer<typeof runStatusSchema>
7
+
8
+ export const runEventTypeSchema = z.enum([
9
+ 'started',
10
+ 'context.snapshot',
11
+ 'message.delta',
12
+ 'message.completed',
13
+ 'tool.started',
14
+ 'tool.completed',
15
+ 'retry.started',
16
+ 'retry.ended',
17
+ 'compaction.started',
18
+ 'compaction.ended',
19
+ 'approval.requested',
20
+ 'approval.resolved',
21
+ 'question.requested',
22
+ 'question.answered',
23
+ 'extension.notice',
24
+ 'reaction.added',
25
+ 'agent.message',
26
+ 'artifact.added',
27
+ 'file.changed',
28
+ 'usage.updated',
29
+ 'account.status',
30
+ 'status.changed',
31
+ 'failed',
32
+ 'completed'
33
+ ])
34
+ export type RunEventType = z.infer<typeof runEventTypeSchema>
35
+
36
+ const messageDeltaPayload = z.object({ messageId: z.string(), text: z.string() })
37
+ const messageCompletedPayload = z.object({ messageId: z.string(), role: z.enum(['user', 'assistant']), text: z.string() })
38
+ const contextSnapshotPayload = z.object({
39
+ systemPrompt: z.string().max(100_000),
40
+ contextUpdate: z.string().max(100_000).optional(),
41
+ tools: z.array(z.object({ name: z.string(), description: z.string().max(2_000), parameters: z.unknown() })).max(120),
42
+ systemPromptTruncated: z.boolean().optional(),
43
+ contextUpdateTruncated: z.boolean().optional(),
44
+ toolsTruncated: z.boolean().optional()
45
+ })
46
+ const toolPayload = z.object({
47
+ toolCallId: z.string(),
48
+ name: z.string(),
49
+ summary: z.string().max(200).optional(),
50
+ input: z.string().max(24_000).optional(),
51
+ inputTruncated: z.boolean().optional(),
52
+ output: z.string().max(24_000).optional(),
53
+ outputTruncated: z.boolean().optional(),
54
+ ok: z.boolean().optional(),
55
+ /** On `tool.completed`: how long the call ran, and the size of what it returned to the model. */
56
+ durationMs: z.number().optional(),
57
+ resultChars: z.number().optional()
58
+ })
59
+ const retryStartedPayload = z.object({ attempt: z.number(), maxAttempts: z.number(), delayMs: z.number(), error: z.string().max(1_000).optional() })
60
+ const retryEndedPayload = z.object({ attempt: z.number(), success: z.boolean(), error: z.string().max(1_000).optional() })
61
+ const compactionStartedPayload = z.object({ reason: z.string() })
62
+ const compactionEndedPayload = z.object({
63
+ reason: z.string(),
64
+ aborted: z.boolean(),
65
+ willRetry: z.boolean().optional(),
66
+ error: z.string().max(1_000).optional(),
67
+ tokensBefore: z.number().optional(),
68
+ tokensAfter: z.number().optional(),
69
+ summary: z.string().max(24_000).optional(),
70
+ summaryTruncated: z.boolean().optional()
71
+ })
72
+ /** Granted without asking: the standing switch, a remembered tool, or the embedding application's own scope. */
73
+ const approvalAutomaticSchema = z.enum(['always', 'remembered', 'scope'])
74
+ const approvalRequestedPayload = z.object({
75
+ approvalId: z.string(),
76
+ target: z.string(),
77
+ action: z.string(),
78
+ screenshotRef: z.string().optional(),
79
+ operation: z.object({ tool: z.string(), args: z.unknown() }).optional(),
80
+ /** A tool the user may choose to always allow for this session. */
81
+ rememberable: z.boolean().optional(),
82
+ /** Set when the request was granted as it was made, so nobody is waiting on it. */
83
+ automatic: approvalAutomaticSchema.optional()
84
+ })
85
+ const approvalResolvedPayload = z.object({ approvalId: z.string(), decision: z.enum(['approved', 'denied', 'native']), automatic: approvalAutomaticSchema.optional() })
86
+ export const questionOptionSchema = z.object({ label: z.string().min(1), description: z.string().optional() })
87
+ export type QuestionOption = z.infer<typeof questionOptionSchema>
88
+ const questionRequestedPayload = z.object({
89
+ questionId: z.string(),
90
+ question: z.string().min(1),
91
+ options: z.array(questionOptionSchema),
92
+ multiSelect: z.boolean(),
93
+ allowText: z.boolean(),
94
+ userOnly: z.boolean().optional()
95
+ })
96
+ const questionAnsweredPayload = z.object({ questionId: z.string(), selected: z.array(z.string()), text: z.string().optional() })
97
+ /** A short emoji sequence, never words or numbers. */
98
+ const reactionAddedPayload = z.object({ emoji: z.string().min(1).refine((text) => Buffer.byteLength(text) <= 16 && !/[A-Za-z0-9\s]/.test(text)) })
99
+ /** A message this run's agent sent to (`to`) or received back from (`from`) another agent. */
100
+ const agentMessagePayload = z.object({ direction: z.enum(['to', 'from']), agentId: z.string(), agentName: z.string(), text: z.string() })
101
+ /** A status line, a notification or an error from a Pi extension loaded in the session. */
102
+ const extensionNoticePayload = z.object({
103
+ kind: z.enum(['notify', 'status', 'widget', 'title', 'error']),
104
+ level: z.enum(['info', 'warning', 'error']).optional(),
105
+ key: z.string().optional(),
106
+ text: z.string(),
107
+ extension: z.string().optional()
108
+ })
109
+ const artifactPayload = z.object({ artifactId: z.string(), name: z.string(), file: z.unknown().optional() })
110
+ const fileChangedPayload = z.object({ path: z.string(), change: z.enum(['added', 'modified', 'deleted']) })
111
+ /** Where a cost figure comes from: Pi reported it, or the tokens were priced at list rates. */
112
+ export const costSourceSchema = z.enum(['harness', 'estimate', 'mixed'])
113
+ export type CostSource = z.infer<typeof costSourceSchema>
114
+ /** What one model request used. Token fields mean the same as on the run's totals. */
115
+ export const usageRequestSchema = z.object({
116
+ /** Position in the run, from 1. */
117
+ index: z.number(),
118
+ responseId: z.string().optional(),
119
+ model: z.string().optional(),
120
+ provider: z.string().optional(),
121
+ inputTokens: z.number().optional(),
122
+ cacheReadTokens: z.number().optional(),
123
+ cacheWriteTokens: z.number().optional(),
124
+ outputTokens: z.number().optional(),
125
+ reasoningTokens: z.number().optional(),
126
+ costUsd: z.number().optional(),
127
+ costSource: z.enum(['harness', 'estimate']).optional(),
128
+ /** Separate provider-supplied summary; never generic private thinking content. */
129
+ reasoningSummary: z.string().max(4_000).optional(),
130
+ /** From sending the request to the end of the response, and to its first output. */
131
+ durationMs: z.number().optional(),
132
+ ttftMs: z.number().optional(),
133
+ stopReason: z.string().optional()
134
+ })
135
+ export type UsageRequest = z.infer<typeof usageRequestSchema>
136
+ /** Token totals so far in this run (cumulative for the run, not the native session). */
137
+ export const usagePayloadSchema = z.object({
138
+ /** Input tokens that were not read from the provider's cache. */
139
+ inputTokens: z.number().optional(),
140
+ /** Includes reasoning tokens. */
141
+ outputTokens: z.number().optional(),
142
+ cacheReadTokens: z.number().optional(),
143
+ cacheWriteTokens: z.number().optional(),
144
+ reasoningTokens: z.number().optional(),
145
+ costUsd: z.number().optional(),
146
+ costSource: costSourceSchema.optional(),
147
+ /** Model requests made so far. */
148
+ requests: z.number().optional(),
149
+ /** Size of the latest request (not cumulative), and the model's limit. */
150
+ contextTokens: z.number().optional(),
151
+ contextWindow: z.number().optional(),
152
+ model: z.string().optional(),
153
+ provider: z.string().optional(),
154
+ /** The request this update reports. */
155
+ request: usageRequestSchema.optional()
156
+ })
157
+ export type UsagePayload = z.infer<typeof usagePayloadSchema>
158
+ export const accountIssueCategorySchema = z.enum(['auth_expired', 'rate_limited', 'quota', 'network', 'unknown'])
159
+ export type AccountIssueCategory = z.infer<typeof accountIssueCategorySchema>
160
+ export const accountLimitSchema = z.object({
161
+ id: z.string(),
162
+ label: z.string(),
163
+ usedPercent: z.number().nullable().optional(),
164
+ resetsAt: z.string().nullable().optional(),
165
+ windowMinutes: z.number().nullable().optional(),
166
+ status: z.string().nullable().optional()
167
+ })
168
+ export type AccountLimit = z.infer<typeof accountLimitSchema>
169
+ /** Limit snapshots, plan changes, and classified account failures. */
170
+ const accountStatusPayload = z.object({
171
+ accountId: z.string(),
172
+ category: accountIssueCategorySchema.optional(),
173
+ message: z.string().optional(),
174
+ resetsAt: z.string().optional(),
175
+ plan: z.string().optional(),
176
+ limits: z.array(accountLimitSchema).optional()
177
+ })
178
+ const statusPayload = z.object({ status: runStatusSchema, reason: z.string().optional() })
179
+ const failedPayload = z.object({ code: z.string(), message: z.string() })
180
+ const emptyPayload = z.object({}).passthrough()
181
+
182
+ /** Payload schema per discriminant. */
183
+ export const runEventPayloadSchemas = {
184
+ started: emptyPayload,
185
+ 'context.snapshot': contextSnapshotPayload,
186
+ 'message.delta': messageDeltaPayload,
187
+ 'message.completed': messageCompletedPayload,
188
+ 'tool.started': toolPayload,
189
+ 'tool.completed': toolPayload,
190
+ 'retry.started': retryStartedPayload,
191
+ 'retry.ended': retryEndedPayload,
192
+ 'compaction.started': compactionStartedPayload,
193
+ 'compaction.ended': compactionEndedPayload,
194
+ 'approval.requested': approvalRequestedPayload,
195
+ 'approval.resolved': approvalResolvedPayload,
196
+ 'question.requested': questionRequestedPayload,
197
+ 'question.answered': questionAnsweredPayload,
198
+ 'extension.notice': extensionNoticePayload,
199
+ 'reaction.added': reactionAddedPayload,
200
+ 'agent.message': agentMessagePayload,
201
+ 'artifact.added': artifactPayload,
202
+ 'file.changed': fileChangedPayload,
203
+ 'usage.updated': usagePayloadSchema,
204
+ 'account.status': accountStatusPayload,
205
+ 'status.changed': statusPayload,
206
+ failed: failedPayload,
207
+ completed: emptyPayload
208
+ } satisfies Record<RunEventType, z.ZodType>
209
+
210
+ export const runEventSchema = z
211
+ .object({
212
+ id: z.string(),
213
+ runId: z.string(),
214
+ sessionId: z.string(),
215
+ sequence: z.number().int().nonnegative(),
216
+ timestamp: z.string(),
217
+ type: runEventTypeSchema,
218
+ payload: z.unknown(),
219
+ /** The native event this one was derived from, kept as evidence. */
220
+ native: z.unknown().optional(),
221
+ /** Set when consecutive text deltas were merged for relay; covers sequences coalescedFrom..sequence. */
222
+ coalescedFrom: z.number().int().nonnegative().optional()
223
+ })
224
+ .superRefine((event, context) => {
225
+ if (!runEventPayloadSchemas[event.type].safeParse(event.payload).success) {
226
+ context.addIssue({ code: 'custom', path: ['payload'], message: `Invalid payload for ${event.type}` })
227
+ }
228
+ })
229
+ export type RunEvent = z.infer<typeof runEventSchema>
230
+
231
+ /**
232
+ * One tracked execution interval of a session. `mode`, `harness`, `sessionType`, `worktreeId`,
233
+ * `attachmentCount`, `exitCode`, `handoffId` and `trigger` belong to the embedding application:
234
+ * the harness stores and returns them, and reads only `mode` (`chat` is an agent's own
235
+ * conversation, `code` is a session in a project).
236
+ */
237
+ export interface RunRecord {
238
+ resumedFromRunId: string | null
239
+ /** Opaque run lineage supplied by the embedding application. */
240
+ parentRunId: string | null
241
+ relation: string | null
242
+ terminalReason: string | null
243
+ id: string
244
+ projectId: string | null
245
+ mode: string
246
+ harness: string
247
+ sessionType: string
248
+ sessionId: string
249
+ nativeSessionId: string | null
250
+ workingDirectory: string | null
251
+ worktreeId: string | null
252
+ goal: string | null
253
+ attachmentCount: number
254
+ startedAt: string
255
+ endedAt: string | null
256
+ status: string
257
+ exitCode: number | null
258
+ handoffId: string | null
259
+ /** The account the run used. */
260
+ accountId: string | null
261
+ /** The agent that replied. */
262
+ agentId: string | null
263
+ /** What started the run. */
264
+ trigger: string | null
265
+ }
266
+
267
+ const text = z.string().nullish().transform((value) => value ?? null)
268
+
269
+ export const runRecordSchema = z.object({
270
+ resumedFromRunId: text,
271
+ parentRunId: text,
272
+ relation: text,
273
+ terminalReason: text,
274
+ id: z.string(),
275
+ projectId: text,
276
+ mode: z.string(),
277
+ harness: z.string(),
278
+ sessionType: z.string(),
279
+ sessionId: z.string(),
280
+ nativeSessionId: text,
281
+ workingDirectory: text,
282
+ worktreeId: text,
283
+ goal: text,
284
+ attachmentCount: z.number().int().nonnegative().default(0),
285
+ startedAt: z.string(),
286
+ endedAt: text,
287
+ status: z.string(),
288
+ exitCode: z.number().int().nullish().transform((value) => value ?? null),
289
+ handoffId: text,
290
+ accountId: text,
291
+ agentId: text,
292
+ trigger: text
293
+ }) satisfies z.ZodType<RunRecord, unknown>
294
+
295
+ export const ACTIVE_STATUSES: readonly string[] = ['queued', 'running', 'waiting_for_approval', 'waiting_for_input']
296
+
297
+ export function isActiveStatus(status: string): boolean {
298
+ return ACTIVE_STATUSES.includes(status)
299
+ }