@pennixrv/trellis-paseo-adapter 0.7.2-beta.29 → 0.7.2-beta.31

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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Optional Paseo adapter
2
2
 
3
- This package is installed explicitly through Pennix Lifecycle. It requires Node 22 or newer
3
+ This package is installed explicitly through Pennix Lifecycle. It requires Node 22.16 or newer
4
4
  and a running local Paseo daemon with the public operations used by the request. The ordinary Trellis CLI/core do not depend on it.
5
5
 
6
6
  `trellis-paseo-adapter` accepts one version-1 JSON request on stdin and returns one bounded
@@ -13,11 +13,38 @@ Paseo server dependencies include native provider/PTY/voice packages. Their inst
13
13
  cost is confined to this optional package and Lifecycle's explicit script allowlist.
14
14
  The packaged SDK is pinned for reproducible installation; daemon admission uses
15
15
  the public server-info identity, operation methods and actual response contracts,
16
- without a daemon version allowlist. Missing identity or required methods, other
16
+ without a general daemon version allowlist. The closed-snapshot background rule
17
+ below is limited to the verified 0.19.1 semantics. Missing identity or required methods, other
17
18
  providers and remote transports are refused. Capability output distinguishes
18
19
  `sdk_version` from the informational `daemon_version`.
19
20
  Bottom-level approval/context settings use native defaults.
20
21
 
22
+ In a Pennix deployment, admission and new work read `pennix config paseo --json`
23
+ and must use its single configured local instance. Missing/incompatible policy
24
+ is an explicit failure, not a fallback to another home. Bound safety operations
25
+ can still observe, interrupt, withdraw and close historical resources in their
26
+ original home. Standalone use without Lifecycle retains native home selection.
27
+
28
+ `prepare-workspace` supports explicit `target_mode: "directory"` as well as the
29
+ default worktree mode. `prepare-agent` accepts an explicit UUID `agent_id` and
30
+ can omit the initial prompt so the controller can publish identity first.
31
+ `execute` and `followup` send `messageId` with native `queue` behavior, including
32
+ when already busy; their receipt does not prove consumption or completion.
33
+
34
+ `queue`, `withdraw` and `timeline` expose bounded native message identities and
35
+ cursor/turn evidence, without prompt or response bodies. Withdrawal distinguishes
36
+ `withdrawn`, `not_found` and `already_dispatching`; an empty queue is not proof
37
+ that an unknown send never happened. `background` and `stop-background` use
38
+ exact item IDs and stop tokens without exposing command bodies. `close-agent` uses the public native MCP `kill_agent` operation to close only the
39
+ provider runtime, preserving history and a queryable, nonarchived Agent. Admission
40
+ requires that tool on the same verified local endpoint. It uses the native local
41
+ credential and respects an authentication denial; it never reads injected Agent
42
+ tokens. The historical explicit `archive-agent` operation remains available, but
43
+ archived Agents cannot provide the inventories needed for new acceptance or reuse. None of these calls alone
44
+ proves that every writer has stopped. `reuse-agent` requires a closed matching
45
+ agent with no queued input or background work; the controller separately owns
46
+ new authorization, context switching and whether reuse is permitted.
47
+
21
48
  `inspect` and `resource-preview` accept optional `page_size` (1–100) and `cursor`.
22
49
  Paged replies include `page_info.next_cursor` and `page_info.complete`; consume
23
50
  every page before concluding that a resource is absent. An `agent_id` uses an
@@ -26,3 +53,11 @@ still require a complete result and fail explicitly at the 256 KiB response
26
53
  boundary. There is no historical-agent count limit; incomplete pages, cursor
27
54
  cycles and excessive responses fail explicitly. Native controller consumers use
28
55
  paging for writer checks and exact IDs or scoped paging for recovery.
56
+
57
+ For official 0.19.1, a fresh closed, nonarchived snapshot without a background
58
+ summary means the provider inventory has been removed and no daemon-owned work
59
+ remains. A registered daemon service still produces a nonzero summary after
60
+ runtime close. The adapter reports this specific snapshot evidence separately
61
+ from the list API; it does not turn a failed list request into an empty result.
62
+ Archived snapshots, active turns and unverified version semantics do not use
63
+ this rule. Queue inventory remains a complete native query after runtime-only close.
package/bin/adapter.js CHANGED
@@ -7,7 +7,8 @@ if (process.argv[2] === '--version') {
7
7
  } else {
8
8
  let request;
9
9
  try {
10
- if (Number(process.versions.node.split('.')[0]) < 22) throw new Error('Node >=22 required');
10
+ const [major, minor] = process.versions.node.split('.').map(Number);
11
+ if (major < 22 || major === 22 && minor < 16) throw new Error('Node >=22.16.0 required');
11
12
  const chunks = [];
12
13
  let bytes = 0;
13
14
  for await (const chunk of process.stdin) {
@@ -22,7 +23,7 @@ if (process.argv[2] === '--version') {
22
23
  process.stdout.write(result + '\n');
23
24
  } catch (error) {
24
25
  // Native messages can contain provider configuration or credentials; expose stable categories only.
25
- const category = error.category ?? (request && !['capability', 'inspect', 'observe', 'wait', 'resource-preview'].includes(request.operation) ? 'outcome_unknown' : request ? 'native_error' : 'invalid_input');
26
+ const category = error.category ?? (request && !['capability', 'inspect', 'observe', 'wait', 'resource-preview', 'queue', 'timeline', 'background'].includes(request.operation) ? 'outcome_unknown' : request ? 'native_error' : 'invalid_input');
26
27
  process.stdout.write(JSON.stringify({ version: 1, operation: request?.operation, attempt_id: request?.attempt_id, binding_revision: request?.binding_revision, ok: false, observations: null, error: { category, message: `Paseo adapter: ${category}; inspect native state before retrying a write.` } }) + '\n');
27
28
  process.exitCode = 1;
28
29
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pennixrv/trellis-paseo-adapter",
3
- "version": "0.7.2-beta.29",
3
+ "version": "0.7.2-beta.31",
4
4
  "description": "Optional local Paseo public SDK adapter for Trellis worktree delegation",
5
5
  "type": "module",
6
6
  "bin": {
@@ -12,11 +12,11 @@
12
12
  "README.md"
13
13
  ],
14
14
  "engines": {
15
- "node": ">=22"
15
+ "node": ">=22.16.0"
16
16
  },
17
17
  "dependencies": {
18
- "@getpaseo/client": "0.15.3",
19
- "@getpaseo/server": "0.15.3"
18
+ "@getpaseo/client": "0.19.1",
19
+ "@getpaseo/server": "0.19.1"
20
20
  },
21
21
  "publishConfig": {
22
22
  "access": "public",
@@ -27,10 +27,13 @@
27
27
  "type": "git",
28
28
  "url": "https://github.com/PennixRv/Trellis.git"
29
29
  },
30
+ "devDependencies": {
31
+ "@getpaseo/cli": "0.19.1"
32
+ },
30
33
  "scripts": {
31
- "build": "node --check bin/adapter.js && node --check src/adapter.js",
34
+ "build": "node --check bin/adapter.js && node --check src/adapter.js && node --check src/native-tools.js",
32
35
  "test": "node --test test/*.test.js",
33
- "lint": "node --check bin/adapter.js && node --check src/adapter.js",
34
- "typecheck": "node --check src/adapter.js"
36
+ "lint": "node --check bin/adapter.js && node --check src/adapter.js && node --check src/native-tools.js",
37
+ "typecheck": "node --check src/adapter.js && node --check src/native-tools.js"
35
38
  }
36
39
  }
package/src/adapter.js CHANGED
@@ -2,10 +2,28 @@ import { accessSync, constants, realpathSync, statSync } from 'node:fs';
2
2
  import { isAbsolute } from 'node:path';
3
3
  import { randomUUID, createHash } from 'node:crypto';
4
4
  import { hostname } from 'node:os';
5
+ import { spawnSync } from 'node:child_process';
6
+ import metadata from '../package.json' with { type: 'json' };
5
7
 
6
8
  export const MAX_BYTES = 256 * 1024;
7
- const operations = new Set(['capability', 'inspect', 'prepare-workspace', 'prepare-agent', 'execute', 'followup', 'observe', 'wait', 'interrupt', 'resource-preview']);
9
+ const operations = new Set(['capability', 'inspect', 'prepare-workspace', 'prepare-agent', 'execute', 'followup', 'observe', 'wait', 'interrupt', 'resource-preview', 'queue', 'withdraw', 'timeline', 'background', 'stop-background', 'archive-agent', 'close-agent', 'reuse-agent']);
10
+ const admissionOperations = new Set(['capability', 'prepare-workspace', 'prepare-agent', 'execute', 'followup', 'reuse-agent']);
8
11
  export function refuse(category) { throw Object.assign(new Error(category), { category }); }
12
+ export function verifyLifecyclePolicy(home, policy) {
13
+ if (policy?.schema_version !== 1 || policy.instance_policy !== 'single' || typeof policy.enabled !== 'boolean' || !isAbsolute(policy.home ?? '')) refuse('unsupported');
14
+ let configured;
15
+ try { configured = realpathSync(policy.home); } catch { refuse('identity_mismatch'); }
16
+ if (!policy.enabled || configured !== home) refuse('identity_mismatch');
17
+ }
18
+ function lifecyclePolicy(home) {
19
+ const result = spawnSync('pennix', ['config', 'paseo', '--json'], { encoding: 'utf8', timeout: 15000, maxBuffer: 16384 });
20
+ if (result.error?.code === 'ENOENT') return null;
21
+ if (result.error || result.status !== 0) refuse('unsupported');
22
+ let policy;
23
+ try { policy = JSON.parse(result.stdout); } catch { refuse('invalid_response'); }
24
+ verifyLifecyclePolicy(home, policy);
25
+ return policy;
26
+ }
9
27
  export function verifyDaemonInfo(info, serverId) {
10
28
  if (info?.serverId !== serverId) refuse('identity_mismatch');
11
29
  if (typeof info.version !== 'string' || !info.version) refuse('unsupported');
@@ -24,26 +42,55 @@ export function validate(request) {
24
42
  if (request.binding_revision != null && !/^[a-f0-9]{64}$/.test(request.binding_revision)) refuse('invalid_input');
25
43
  const fields = {
26
44
  capability: ['cwd'], inspect: ['target', 'workspace_id', 'agent_id', 'cursor', 'page_size'], 'resource-preview': ['target', 'workspace_id', 'agent_id', 'cursor', 'page_size'],
27
- 'prepare-workspace': ['target', 'branch', 'base_commit', 'title'],
28
- 'prepare-agent': ['workspace_id', 'cwd', 'model', 'effort', 'role', 'context', 'prompt', 'codegraph', 'codegraph_command', 'labels'],
45
+ 'prepare-workspace': ['target', 'branch', 'base_commit', 'title', 'target_mode'],
46
+ 'prepare-agent': ['workspace_id', 'cwd', 'agent_id', 'model', 'effort', 'role', 'context', 'prompt', 'codegraph', 'codegraph_command', 'labels'],
29
47
  execute: ['agent_id', 'cwd', 'prompt', 'client_message_id'], followup: ['agent_id', 'cwd', 'prompt', 'client_message_id'],
30
48
  observe: ['agent_id', 'cwd'], wait: ['agent_id', 'cwd', 'timeout_ms'], interrupt: ['agent_id', 'cwd'],
49
+ queue: ['agent_id', 'cwd'], withdraw: ['agent_id', 'cwd', 'client_message_id'],
50
+ timeline: ['agent_id', 'cwd', 'cursor', 'direction', 'limit'],
51
+ background: ['agent_id', 'cwd'], 'stop-background': ['agent_id', 'cwd', 'item_id', 'stop_token'],
52
+ 'archive-agent': ['agent_id', 'cwd'], 'close-agent': ['agent_id', 'cwd'],
53
+ 'reuse-agent': ['agent_id', 'cwd', 'workspace_id', 'previous_attempt_id', 'model', 'effort', 'labels'],
31
54
  };
32
55
  keys(request.payload ?? {}, fields[request.operation]);
33
56
  for (const [key, value] of Object.entries(request.payload ?? {})) {
34
57
  if (key === 'codegraph') { if (typeof value !== 'boolean') refuse('invalid_input'); }
35
58
  else if (key === 'timeout_ms') { if (!Number.isInteger(value) || value < 1 || value > 3600000) refuse('invalid_input'); }
36
59
  else if (key === 'page_size') { if (!Number.isInteger(value) || value < 1 || value > 100) refuse('invalid_input'); }
60
+ else if (key === 'limit') { if (!Number.isInteger(value) || value < 1 || value > 100) refuse('invalid_input'); }
61
+ else if (key === 'cursor' && request.operation === 'timeline') {
62
+ keys(value, ['epoch', 'seq']);
63
+ text(value.epoch);
64
+ if (!Number.isInteger(value.seq) || value.seq < 0) refuse('invalid_input');
65
+ }
66
+ else if (key === 'target_mode') { if (!['directory', 'worktree'].includes(value)) refuse('invalid_input'); }
67
+ else if (key === 'direction') { if (!['tail', 'before', 'after'].includes(value)) refuse('invalid_input'); }
68
+ else if (key === 'agent_id' && request.operation === 'prepare-agent') {
69
+ if (typeof value !== 'string' || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value)) refuse('invalid_input');
70
+ }
37
71
  else if (key === 'labels') { keys(value, ['trellis.control', 'trellis.child', 'trellis.attempt']); Object.values(value).forEach(text); }
38
72
  else text(value);
39
73
  }
40
74
  for (const value of Object.values(request.daemon_selector ?? {})) text(value);
41
75
  return request;
42
76
  }
77
+ export async function backgroundInventory(ref, client) {
78
+ const snapshot = ref.current(), info = client.getLastServerInfoMessage?.();
79
+ // Verified 0.19.1 removes provider inventory on runtime close. A nonarchived
80
+ // stored snapshot still includes every daemon-owned item's summary.
81
+ if (info?.version === '0.19.1' && info.features?.agentBackgroundWork === true
82
+ && snapshot?.status === 'closed' && !snapshot.activeTurn && snapshot.archivedAt === null
83
+ && snapshot.backgroundWork === undefined) {
84
+ return { items: [], evidence: 'closed_nonarchived_snapshot_v0.19.1' };
85
+ }
86
+ const items = await client.listAgentBackgroundWork(ref.id);
87
+ if (!Array.isArray(items)) refuse('invalid_response');
88
+ return { items, evidence: 'native_inventory' };
89
+ }
43
90
  function projectAgent(agent) {
44
91
  if (!agent) return null;
45
- const result = Object.fromEntries(['id', 'workspaceId', 'cwd', 'provider', 'model', 'status', 'thinkingOptionId', 'effectiveThinkingOptionId', 'labels'].map(k => [k, agent[k] ?? null]));
46
- result.activeTurn = agent.activeTurn ? { id: agent.activeTurn.id ?? null } : null;
92
+ const result = Object.fromEntries(['id', 'workspaceId', 'cwd', 'provider', 'model', 'status', 'archivedAt', 'backgroundWork', 'currentModeId', 'thinkingOptionId', 'effectiveThinkingOptionId', 'labels'].map(k => [k, agent[k] ?? null]));
93
+ result.activeTurn = agent.activeTurn ? { id: agent.activeTurn.turnId ?? null } : null;
47
94
  result.runtimeInfo = agent.runtimeInfo ? Object.fromEntries(['provider', 'model', 'modeId', 'thinkingOptionId'].map(k => [k, agent.runtimeInfo[k] ?? null])) : null;
48
95
  return result;
49
96
  }
@@ -51,31 +98,52 @@ function workspace(w) {
51
98
  if (!w) return null;
52
99
  return Object.fromEntries(['id', 'projectId', 'projectRootPath', 'workspaceDirectory', 'workspaceKind', 'setupStatus', 'status', 'branch'].map(k => [k, w[k] ?? null]));
53
100
  }
54
- export async function perform(request, api, client, identity) {
55
- const p = request.payload ?? {}, op = request.operation;
101
+ export async function perform(request, api, client, identity, tools = {}) {
102
+ const p = request.payload ?? {}, op = request.operation === 'resource-preview' ? 'inspect' : request.operation;
56
103
  const methods = {
57
104
  capability: [[api.providers, 'listModels'], [api.providers, 'listModes']],
58
105
  'prepare-workspace': [[api.workspaces, 'create']],
59
106
  'prepare-agent': [[api.workspaces, 'ref']],
60
- execute: [[api.agents, 'ref']], followup: [[api.agents, 'ref']],
107
+ execute: [[api.agents, 'ref'], [client, 'sendAgentMessage']], followup: [[api.agents, 'ref'], [client, 'sendAgentMessage']],
61
108
  observe: [[api.agents, 'ref']], wait: [[api.agents, 'ref']], interrupt: [[api.agents, 'ref'], [client, 'cancelAgent']],
62
109
  inspect: [[api.agents, p.agent_id ? 'ref' : 'list'], [api.config, 'get'], [api.projects, 'list']],
63
- 'resource-preview': [[api.agents, p.agent_id ? 'ref' : 'list'], [api.config, 'get'], [api.projects, 'list']],
110
+ queue: [[api.agents, 'ref'], [client, 'listAgentQueue']],
111
+ withdraw: [[api.agents, 'ref'], [client, 'withdrawAgentQueueItem']],
112
+ timeline: [[api.agents, 'ref'], [client, 'fetchAgentTimeline']],
113
+ background: [[api.agents, 'ref'], [client, 'listAgentBackgroundWork']],
114
+ 'stop-background': [[api.agents, 'ref'], [client, 'stopAgentBackgroundWork'], [client, 'listAgentBackgroundWork']],
115
+ 'archive-agent': [[api.agents, 'ref'], [client, 'archiveAgent']],
116
+ 'close-agent': [[api.agents, 'ref'], [tools, 'close']],
117
+ 'reuse-agent': [[api.agents, 'ref'], [client, 'listAgentQueue'], [client, 'listAgentBackgroundWork'], [client, 'updateAgent'], [client, 'refreshAgent']],
64
118
  };
65
119
  if (methods[op]?.some(([object, key]) => typeof object?.[key] !== 'function')) refuse('unsupported');
66
120
  async function agent() {
67
121
  const ref = api.agents.ref(text(p.agent_id));
68
122
  await ref.refresh();
69
123
  const current = ref.current();
70
- if (!current || current.id !== p.agent_id || realpathSync(current.cwd) !== realpathSync(text(p.cwd))) refuse('identity_mismatch');
124
+ const expectedCwd = text(p.cwd);
125
+ if (!current || current.id !== p.agent_id) refuse('identity_mismatch');
126
+ const attempt = op === 'reuse-agent' ? text(p.previous_attempt_id) : request.attempt_id;
127
+ if (current.labels?.['trellis.attempt'] !== attempt) refuse('identity_mismatch');
128
+ if (admissionOperations.has(op)) {
129
+ if (realpathSync(current.cwd) !== realpathSync(expectedCwd)) refuse('identity_mismatch');
130
+ } else if (current.cwd !== expectedCwd || !isAbsolute(expectedCwd)) refuse('identity_mismatch');
71
131
  return ref;
72
132
  }
73
133
  if (op === 'capability') {
74
134
  const cwd = text(p.cwd);
75
- return { identity, sdk_version: '0.15.3', daemon_version: client.getLastServerInfoMessage().version, protocol: 1, models: await api.providers.listModels('codex', { cwd }), modes: await api.providers.listModes('codex', { cwd }) };
135
+ const info = client.getLastServerInfoMessage();
136
+ return { identity, sdk_version: metadata.dependencies['@getpaseo/client'], daemon_version: info.version, protocol: 1,
137
+ features: { queue: info.features?.nonAgentMessageQueue === true, queue_management: info.features?.agentMessageQueue === true, background_work: info.features?.agentBackgroundWork === true,
138
+ runtime_close: typeof tools.canClose === 'function' && await tools.canClose() },
139
+ models: await api.providers.listModels('codex', { cwd }), modes: await api.providers.listModes('codex', { cwd }) };
76
140
  }
77
141
  if (op === 'prepare-workspace') {
78
- const ref = await api.workspaces.create({ source: { kind: 'worktree', cwd: realpathSync(text(p.target)), action: 'branch-off', baseBranch: text(p.base_commit), branchName: text(p.branch) }, title: text(p.title), background: true });
142
+ const target = realpathSync(text(p.target));
143
+ const source = p.target_mode === 'directory' ? { kind: 'directory', path: target }
144
+ : { kind: 'worktree', cwd: target, action: 'branch-off', baseBranch: text(p.base_commit), branchName: text(p.branch) };
145
+ const ref = await api.workspaces.create({ source, title: text(p.title), background: true,
146
+ idempotencyKey: createHash('sha256').update(JSON.stringify([request.attempt_id, request.binding_revision, source])).digest('hex') });
79
147
  await ref.refresh();
80
148
  return { identity, workspace: workspace(ref.current()) };
81
149
  }
@@ -89,16 +157,89 @@ export async function perform(request, api, client, identity) {
89
157
  // The daemon may have a narrower PATH than the controller that admitted the tool.
90
158
  config.mcpServers = { codegraph: { type: 'stdio', command, args: ['serve', '--mcp', '--bound-worktree', cwd] } };
91
159
  }
92
- const fingerprint = JSON.stringify({ config, cwd, context: p.context, prompt: p.prompt, labels: p.labels });
93
- const ref = await api.workspaces.ref(text(p.workspace_id)).agents.create({ config, env: { TRELLIS_DELEGATION_CONTEXT: text(p.context) }, prompt: text(p.prompt), labels: p.labels, idempotencyKey: createHash('sha256').update(request.attempt_id + request.binding_revision + fingerprint).digest('hex') });
160
+ const fingerprint = JSON.stringify({ config, cwd, workspace: p.workspace_id, agent: p.agent_id, context: p.context, prompt: p.prompt, labels: p.labels });
161
+ const ref = await api.workspaces.ref(text(p.workspace_id)).agents.create({ config, env: { TRELLIS_DELEGATION_CONTEXT: text(p.context) },
162
+ ...(p.agent_id ? { agentId: text(p.agent_id) } : {}), ...(p.prompt ? { prompt: text(p.prompt) } : {}),
163
+ labels: p.labels, idempotencyKey: createHash('sha256').update(request.attempt_id + request.binding_revision + fingerprint).digest('hex') });
94
164
  await ref.refresh();
95
165
  return { identity, agent: projectAgent(ref.current()) };
96
166
  }
97
167
  if (['execute', 'followup'].includes(op)) {
98
168
  const ref = await agent();
99
- if (ref.activeTurn || ref.status !== 'idle') refuse('identity_mismatch');
100
- await ref.send(text(p.prompt), { clientMessageId: text(p.client_message_id) });
101
- return { identity, send_returned: true, delivery_proven: false, agent_id: ref.id };
169
+ if (client.getLastServerInfoMessage()?.features?.nonAgentMessageQueue !== true) refuse('unsupported');
170
+ const messageId = text(p.client_message_id);
171
+ const receipt = await client.sendAgentMessage(ref.id, text(p.prompt), { messageId, activeTurnBehavior: 'queue' });
172
+ if (receipt?.messageId && receipt.messageId !== messageId) refuse('invalid_response');
173
+ return { identity, send_returned: true, delivery_proven: false, agent_id: ref.id, message_id: messageId, receipt };
174
+ }
175
+ if (['queue', 'withdraw', 'reuse-agent'].includes(op)) {
176
+ const ref = await agent();
177
+ if (client.getLastServerInfoMessage()?.features?.agentMessageQueue !== true) refuse('unsupported');
178
+ if (op === 'withdraw') {
179
+ const messageId = text(p.client_message_id);
180
+ const result = await client.withdrawAgentQueueItem(ref.id, messageId);
181
+ if (result?.withdrawn === true && result.item?.id === messageId) return { identity, message_id: messageId, withdrawn: true };
182
+ if (result?.withdrawn === false && ['not_found', 'already_dispatching'].includes(result.reason)) return { identity, message_id: messageId, withdrawn: false, reason: result.reason };
183
+ refuse('invalid_response');
184
+ }
185
+ const queue = await client.listAgentQueue(ref.id);
186
+ if (typeof queue?.held !== 'boolean' || !Array.isArray(queue.items)) refuse('invalid_response');
187
+ const items = queue.items.map(item => {
188
+ if (!item || typeof item.id !== 'string' || !Number.isInteger(item.seq) || !['queued', 'dispatching'].includes(item.state) || typeof item.held !== 'boolean') refuse('invalid_response');
189
+ return { id: item.id, seq: item.seq, state: item.state, held: item.held };
190
+ });
191
+ if (new Set(items.map(item => item.id)).size !== items.length) refuse('invalid_response');
192
+ if (op === 'queue') return { identity, held: queue.held, items };
193
+ const current = ref.current();
194
+ if (current.status !== 'closed' || current.activeTurn || current.workspaceId !== p.workspace_id
195
+ || current.labels?.['trellis.attempt'] !== p.previous_attempt_id || items.length
196
+ || current.provider !== 'codex' || current.model !== text(p.model) || current.currentModeId !== 'full-access'
197
+ || (current.effectiveThinkingOptionId ?? current.thinkingOptionId) !== text(p.effort)
198
+ || (await backgroundInventory(ref, client)).items.length) refuse('identity_mismatch');
199
+ await client.updateAgent(ref.id, { labels: p.labels });
200
+ await client.refreshAgent(ref.id);
201
+ await ref.refresh();
202
+ return { identity, agent: projectAgent(ref.current()) };
203
+ }
204
+ if (op === 'timeline') {
205
+ const ref = await agent();
206
+ const page = await client.fetchAgentTimeline(ref.id, { direction: p.direction ?? (p.cursor ? 'after' : 'tail'), cursor: p.cursor, limit: p.limit ?? 100 });
207
+ if (page?.error || !Array.isArray(page?.entries) || typeof page.epoch !== 'string'
208
+ || ['reset', 'staleCursor', 'gap', 'hasOlder', 'hasNewer'].some(key => typeof page[key] !== 'boolean')) refuse('invalid_response');
209
+ return { identity, epoch: page.epoch, reset: page.reset, stale_cursor: page.staleCursor, gap: page.gap,
210
+ has_older: page.hasOlder, has_newer: page.hasNewer, start_cursor: page.startCursor, end_cursor: page.endCursor,
211
+ entries: page.entries.map(row => {
212
+ if (!row?.item || !Number.isInteger(row.seqStart) || !Number.isInteger(row.seqEnd)) refuse('invalid_response');
213
+ return { kind: row.item.type, turn_id: row.turnId ?? null, seq_start: row.seqStart, seq_end: row.seqEnd,
214
+ message_ids: row.item.type === 'user_message' ? [...new Set([row.item.clientMessageId, row.item.messageId].filter(id => typeof id === 'string'))] : [] };
215
+ }) };
216
+ }
217
+ if (['background', 'stop-background'].includes(op)) {
218
+ const ref = await agent();
219
+ const { items, evidence } = await backgroundInventory(ref, client);
220
+ if (op === 'stop-background') {
221
+ const item = items.find(item => item.id === text(p.item_id) && item.stopToken === text(p.stop_token));
222
+ if (!item || item.canStop !== true) refuse('identity_mismatch');
223
+ await client.stopAgentBackgroundWork(ref.id, item);
224
+ return { identity, item_id: item.id, stop_returned: true, writer_stop_proven: false };
225
+ }
226
+ return { identity, evidence, items: items.map(item => {
227
+ if (typeof item.id !== 'string' || typeof item.kind !== 'string' || typeof item.startedAt !== 'string') refuse('invalid_response');
228
+ return { id: item.id, kind: item.kind, started_at: item.startedAt,
229
+ can_stop: item.canStop === true, stop_token: item.stopToken ?? null };
230
+ }) };
231
+ }
232
+ if (op === 'archive-agent') {
233
+ const ref = await agent();
234
+ await client.archiveAgent(ref.id);
235
+ await ref.refresh();
236
+ return { identity, agent: projectAgent(ref.current()), writer_stop_proven: false };
237
+ }
238
+ if (op === 'close-agent') {
239
+ const ref = await agent();
240
+ await tools.close(ref.id);
241
+ await ref.refresh();
242
+ return { identity, agent: projectAgent(ref.current()), writer_stop_proven: false };
102
243
  }
103
244
  if (['observe', 'wait', 'interrupt'].includes(op)) {
104
245
  const ref = await agent();
@@ -154,10 +295,12 @@ export async function perform(request, api, client, identity) {
154
295
  }
155
296
  export async function dispatch(input) {
156
297
  const request = validate(input);
157
- const { createHostClient } = await import('@getpaseo/client/node');
298
+ const { createHostClient, parseHostTarget } = await import('@getpaseo/client/node');
299
+ const { nativeTools } = await import('./native-tools.js');
158
300
  const { createPaseoApi } = await import('@getpaseo/client');
159
301
  const { resolvePaseoHome, readDaemonInstance, waitForDaemonReady, isSameDaemonInstance, readLocalCredentialForTarget } = await import('@getpaseo/server/daemon-control');
160
302
  const home = realpathSync(request.daemon_selector?.home ?? resolvePaseoHome(process.env));
303
+ const policy = admissionOperations.has(request.operation) ? lifecyclePolicy(home) : null;
161
304
  const original = await readDaemonInstance(home);
162
305
  if (!original) refuse('unavailable');
163
306
  const instance = await waitForDaemonReady(home, { timeoutMs: 15000, instance: original });
@@ -170,6 +313,8 @@ export async function dispatch(input) {
170
313
  verifyDaemonInfo(client.getLastServerInfoMessage(), instance.serverId);
171
314
  if (!isSameDaemonInstance(instance, await readDaemonInstance(home))) refuse('identity_mismatch');
172
315
  api = createPaseoApi(client);
173
- return await perform(request, api, client, { server_id: instance.serverId, home, pid: instance.pid, started_at: instance.startedAt });
316
+ const observations = await perform(request, api, client, { server_id: instance.serverId, home, pid: instance.pid, started_at: instance.startedAt },
317
+ nativeTools(parseHostTarget(instance.listen), readLocalCredentialForTarget(home, instance.listen)));
318
+ return policy ? { ...observations, lifecycle_policy: policy } : observations;
174
319
  } finally { if (api) await api.dispose(); await client.close(); }
175
320
  }
@@ -0,0 +1,79 @@
1
+ import http from 'node:http';
2
+ import https from 'node:https';
3
+ import { randomUUID } from 'node:crypto';
4
+
5
+ const MAX_BYTES = 256 * 1024;
6
+ function failure(category) { return Object.assign(new Error(category), { category }); }
7
+
8
+ // Paseo exposes runtime-only kill_agent through its public stateless MCP endpoint.
9
+ // Use the native endpoint and credential; never inspect an agent's injected tokens.
10
+ async function callNativeTool(target, credential, method, params) {
11
+ const id = randomUUID();
12
+ const body = JSON.stringify({ jsonrpc: '2.0', id, method, params });
13
+ const url = target.socketPath ? new URL('http://localhost/mcp/agents') : new URL(target.url);
14
+ url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:';
15
+ url.pathname = '/mcp/agents';
16
+ url.search = '';
17
+ const transport = url.protocol === 'https:' ? https : http;
18
+ return new Promise((resolve, reject) => {
19
+ const request = transport.request(url, {
20
+ ...(target.socketPath ? { socketPath: target.socketPath } : {}),
21
+ method: 'POST',
22
+ headers: {
23
+ 'Content-Type': 'application/json',
24
+ Accept: 'application/json, text/event-stream',
25
+ 'MCP-Protocol-Version': '2025-03-26',
26
+ 'Content-Length': Buffer.byteLength(body),
27
+ ...(credential ? { Authorization: `Bearer ${credential}` } : {}),
28
+ },
29
+ }, response => {
30
+ if (response.statusCode !== 200) {
31
+ response.resume();
32
+ reject(failure(response.statusCode === 401 || response.statusCode === 403 ? 'unauthorized' : 'unsupported'));
33
+ return;
34
+ }
35
+ const chunks = [];
36
+ let bytes = 0;
37
+ response.on('error', reject);
38
+ response.on('data', chunk => {
39
+ bytes += chunk.length;
40
+ if (bytes > MAX_BYTES) response.destroy(failure('response_limit'));
41
+ else chunks.push(chunk);
42
+ });
43
+ response.on('end', () => {
44
+ try {
45
+ const text = Buffer.concat(chunks).toString('utf8');
46
+ const type = response.headers['content-type']?.split(';')[0].trim();
47
+ const replies = type === 'application/json' ? [JSON.parse(text)]
48
+ : type === 'text/event-stream' ? text.split(/\r?\n\r?\n/).flatMap(event => {
49
+ const data = event.split(/\r?\n/).filter(line => line.startsWith('data:'))
50
+ .map(line => line.slice(5).replace(/^ /, '')).join('\n');
51
+ return data ? [JSON.parse(data)] : [];
52
+ }) : [];
53
+ const matches = replies.filter(reply => reply.jsonrpc === '2.0' && reply.id === id);
54
+ if (matches.length !== 1) throw failure('invalid_response');
55
+ if (matches[0].error) throw failure('native_error');
56
+ resolve(matches[0].result);
57
+ } catch (error) { reject(error.category ? error : failure('invalid_response')); }
58
+ });
59
+ });
60
+ request.setTimeout(60000, () => request.destroy(failure('outcome_unknown')));
61
+ request.on('error', reject);
62
+ request.end(body);
63
+ });
64
+ }
65
+
66
+ export function nativeTools(target, credential) {
67
+ return {
68
+ async canClose() {
69
+ const result = await callNativeTool(target, credential, 'tools/list', {});
70
+ return Array.isArray(result?.tools) && result.tools.some(tool => tool.name === 'kill_agent'
71
+ && tool.inputSchema?.properties?.agentId?.type === 'string');
72
+ },
73
+ async close(agentId) {
74
+ const result = await callNativeTool(target, credential, 'tools/call',
75
+ { name: 'kill_agent', arguments: { agentId } });
76
+ if (result?.isError || result?.structuredContent?.success !== true) throw failure('native_error');
77
+ },
78
+ };
79
+ }