talentos 1.1.6 → 1.3.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.
@@ -1,7 +1,7 @@
1
1
  import { execFile, spawn } from "node:child_process";
2
2
  import { existsSync } from "node:fs";
3
3
  import { rm } from "node:fs/promises";
4
- import { dirname, join } from "node:path";
4
+ import { delimiter, dirname, join } from "node:path";
5
5
  import { createInterface } from "node:readline";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { promisify } from "node:util";
@@ -11,6 +11,8 @@ import { gatewayLauncherPath } from "../gateway-install.js";
11
11
  import { providerPathEnv, resolveProviderBinary } from "../provider-binary.js";
12
12
  import { codexRoomArgs, ROOM_TOOLS } from "./codex-policy.js";
13
13
  import { CodexBoundaryError, probeCodexBoundary } from "./codex-probe.js";
14
+ import { prepareOwnerLaunch } from "./native/launch.js";
15
+ import { readReceipts } from "./native/receipts.js";
14
16
  const CHILD_ENV = [
15
17
  "HOME",
16
18
  "PATH",
@@ -190,7 +192,27 @@ export async function runProvider(input) {
190
192
  const catalogPath = join(dirname(workDir), ".talentos-codex-models.json");
191
193
  const binary = resolveProviderBinary(config.provider, config.providerPath);
192
194
  let command, args;
193
- if (config.provider === "claude_code") {
195
+ let ownerLaunch;
196
+ let stopWatching;
197
+ if (input.owner && config.provider === "claude_code") {
198
+ const watching = await input.owner.watch?.();
199
+ stopWatching = watching?.stop;
200
+ ownerLaunch = await prepareOwnerLaunch({
201
+ agentId: config.agentId,
202
+ askSocket: watching?.socketPath,
203
+ directory: dirname(workDir),
204
+ home: input.owner.home,
205
+ instructions,
206
+ jobId: job.jobId,
207
+ prompt,
208
+ sessionId,
209
+ sharedRoom: job.native?.sharedRoom,
210
+ workspace: input.owner.workspace,
211
+ });
212
+ command = binary;
213
+ args = ownerLaunch.args;
214
+ }
215
+ else if (config.provider === "claude_code") {
194
216
  await writePrivateFile(mcpPath, JSON.stringify({
195
217
  mcpServers: {
196
218
  talentos: {
@@ -249,11 +271,26 @@ export async function runProvider(input) {
249
271
  });
250
272
  }
251
273
  const child = spawn(command, args, {
252
- cwd: workDir,
253
- env: childEnvironment(process.env, binary),
274
+ cwd: input.owner?.workspace.cwd ?? workDir,
275
+ env: input.owner
276
+ ? {
277
+ ...input.owner.env,
278
+ PATH: [dirname(binary), input.owner.env.PATH]
279
+ .filter(Boolean)
280
+ .join(delimiter),
281
+ }
282
+ : childEnvironment(process.env, binary),
254
283
  stdio: ["ignore", "pipe", "ignore"],
255
284
  detached: process.platform !== "win32",
256
285
  });
286
+ const marked = new Set();
287
+ const mark = (name) => {
288
+ if (!marked.has(name)) {
289
+ marked.add(name);
290
+ input.mark?.(name);
291
+ }
292
+ };
293
+ child.once("spawn", () => mark("spawn"));
257
294
  let killTimer;
258
295
  const stop = () => {
259
296
  const pid = child.pid;
@@ -302,6 +339,10 @@ export async function runProvider(input) {
302
339
  continue;
303
340
  }
304
341
  const event = readProviderEvent(config.provider, value);
342
+ mark("firstEvent");
343
+ if (event.status) {
344
+ mark("firstTool");
345
+ }
305
346
  if (event.failed) {
306
347
  failed = true;
307
348
  }
@@ -309,7 +350,8 @@ export async function runProvider(input) {
309
350
  await input.remember(event.sessionId);
310
351
  }
311
352
  if (event.status) {
312
- input.status(event.status);
353
+ // Room-visible status never names the owner's private tools.
354
+ input.status(ownerLaunch ? "Working on your computer…" : event.status);
313
355
  }
314
356
  if (event.text !== undefined) {
315
357
  text = event.text.slice(0, 12_000);
@@ -334,5 +376,13 @@ export async function runProvider(input) {
334
376
  }
335
377
  await rm(mcpPath, { force: true });
336
378
  await rm(catalogPath, { force: true });
379
+ stopWatching?.();
380
+ if (ownerLaunch && input.receipts) {
381
+ // Best effort: a lost record never changes how the job ended.
382
+ await readReceipts(ownerLaunch.jobDir)
383
+ .then((rows) => (rows.length > 0 ? input.receipts?.(rows) : undefined))
384
+ .catch(() => undefined);
385
+ }
386
+ await ownerLaunch?.cleanup();
337
387
  }
338
388
  }
@@ -7,6 +7,11 @@ export const ROOM_TOOLS = [
7
7
  "suggest_change",
8
8
  "create_file",
9
9
  "create_deck",
10
+ "create_web_app",
11
+ "revise_web_app",
12
+ "upload_file",
13
+ "prepare_upload",
14
+ "commit_upload",
10
15
  "post_message",
11
16
  "share_link",
12
17
  "whoami",
@@ -36,7 +36,9 @@ export class AgentGateway {
36
36
  }
37
37
  return response.status === 204 ? null : (await response.json());
38
38
  }
39
- async subscribe(wake, fallback) {
39
+ async subscribe(wake, fallback,
40
+ // Jobs of this agent that were cancelled (the owner's Stop): end them now.
41
+ stopped) {
40
42
  const initial = await this.request("/agent-gateway/token");
41
43
  if (!(initial && isSecureUrl(new URL(initial.convexUrl)))) {
42
44
  throw new Error("Agent push is unavailable.");
@@ -62,8 +64,12 @@ export class AgentGateway {
62
64
  wake();
63
65
  }
64
66
  }, () => fallback());
67
+ const unsubscribeStops = stopped
68
+ ? client.onUpdate(makeFunctionReference("externalAgents/jobs:jobControl"), {}, (jobIds) => stopped(jobIds), () => undefined)
69
+ : undefined;
65
70
  return async () => {
66
71
  unsubscribe();
72
+ unsubscribeStops?.();
67
73
  await client.close();
68
74
  };
69
75
  }
@@ -4,8 +4,11 @@ import { AgentClient } from "../client.js";
4
4
  import { startMcpProxy } from "../mcp-proxy.js";
5
5
  // A local stdio entry avoids putting the bearer key in Codex's argv or child
6
6
  // environment. Only the MCP proxy reads the linked-agent credential file.
7
- const config = (await localAgents()).find((agent) => agent.agentId === parseArgv(process.argv.slice(2)).options.agent);
7
+ const { options } = parseArgv(process.argv.slice(2));
8
+ const config = (await localAgents()).find((agent) => agent.agentId === options.agent);
8
9
  if (!config) {
9
10
  throw new Error("Linked agent configuration is unavailable.");
10
11
  }
11
- await startMcpProxy(new AgentClient({ apiUrl: config.apiUrl, apiKey: config.apiKey }));
12
+ await startMcpProxy(new AgentClient({ apiUrl: config.apiUrl, apiKey: config.apiKey }),
13
+ // The launcher names the job's workspace; a job with none uploads nothing.
14
+ options["upload-root"]);
@@ -0,0 +1,240 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { createServer } from "node:net";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ // The supervisor's half of an ask (#10987 PR 2). The hook (a separate process,
6
+ // inside the provider) connects to this process over a unix socket, sends the
7
+ // ask, and WAITS ON THAT CONNECTION. Nothing is ever read back from a file: an
8
+ // answer exists only as bytes this process writes on the asker's own connection,
9
+ // after the server said so. There is no decision file for the model to forge.
10
+ //
11
+ // The socket lives in a fresh 0700 directory under the system temp folder, never
12
+ // inside any workspace or the job folder. Code that runs as the same user (an
13
+ // approved script) could still impersonate this process; that needs running
14
+ // code, which is itself an owner-approved tier 1 action.
15
+ const ACTION_KEY = /^[0-9a-f]{64}$/u;
16
+ const STATUS_EVERY_MS = 1000;
17
+ const MAX_LINE = 4096;
18
+ const asAnswer = (status) => status === "approved" || status === "denied" || status === "expired"
19
+ ? status
20
+ : undefined;
21
+ function parseReport(line) {
22
+ try {
23
+ const value = JSON.parse(line);
24
+ if (value.touch === true || value.taint === true) {
25
+ return { taint: value.taint === true, touch: value.touch === true };
26
+ }
27
+ }
28
+ catch {
29
+ // Not a report.
30
+ }
31
+ return;
32
+ }
33
+ function parseAsk(line) {
34
+ try {
35
+ const value = JSON.parse(line);
36
+ if (typeof value.actionKey === "string" &&
37
+ ACTION_KEY.test(value.actionKey) &&
38
+ typeof value.kind === "string" &&
39
+ value.kind.length <= 80 &&
40
+ typeof value.summary === "string" &&
41
+ value.summary.length <= 200 &&
42
+ (value.tier === 1 || value.tier === 2)) {
43
+ return {
44
+ actionKey: value.actionKey,
45
+ kind: value.kind,
46
+ summary: value.summary,
47
+ tier: value.tier,
48
+ };
49
+ }
50
+ }
51
+ catch {
52
+ // Not an ask.
53
+ }
54
+ return;
55
+ }
56
+ export class ApprovalBridge {
57
+ gateway;
58
+ onWaiting;
59
+ statusEveryMs;
60
+ waiters = new Map();
61
+ reported = {
62
+ taint: undefined,
63
+ touch: undefined,
64
+ };
65
+ waiting = false;
66
+ polling = false;
67
+ lastPollAt = 0;
68
+ constructor(input) {
69
+ this.gateway = input.gateway;
70
+ this.onWaiting = input.onWaiting ?? (() => undefined);
71
+ this.statusEveryMs = input.statusEveryMs ?? STATUS_EVERY_MS;
72
+ }
73
+ /** Listens for the hook's asks; `stop` refuses anything still held. */
74
+ async start() {
75
+ const directory = mkdtempSync(join(tmpdir(), "tos-"));
76
+ const socketPath = join(directory, "a.sock");
77
+ const server = createServer((socket) => this.accept(socket));
78
+ await new Promise((resolve, reject) => {
79
+ server.once("error", reject);
80
+ server.listen(socketPath, resolve);
81
+ });
82
+ const timer = setInterval(() => {
83
+ this.poll().catch(() => undefined);
84
+ }, Math.max(100, Math.min(this.statusEveryMs, 250)));
85
+ return {
86
+ socketPath,
87
+ stop: () => {
88
+ clearInterval(timer);
89
+ for (const sockets of this.waiters.values()) {
90
+ for (const socket of sockets) {
91
+ socket.destroy();
92
+ }
93
+ }
94
+ this.waiters.clear();
95
+ this.signal();
96
+ server.close();
97
+ rmSync(directory, { force: true, recursive: true });
98
+ },
99
+ };
100
+ }
101
+ accept(socket) {
102
+ let buffer = "";
103
+ socket.setEncoding("utf8");
104
+ socket.on("error", () => socket.destroy());
105
+ socket.on("data", (chunk) => {
106
+ buffer += chunk;
107
+ if (buffer.length > MAX_LINE) {
108
+ socket.destroy();
109
+ return;
110
+ }
111
+ const end = buffer.indexOf("\n");
112
+ if (end < 0) {
113
+ return;
114
+ }
115
+ const line = buffer.slice(0, end);
116
+ buffer = "";
117
+ const report = parseReport(line);
118
+ if (report) {
119
+ this.report(report, socket);
120
+ return;
121
+ }
122
+ const ask = parseAsk(line);
123
+ if (!ask) {
124
+ socket.destroy();
125
+ return;
126
+ }
127
+ this.forward(ask, socket).catch(() => socket.destroy());
128
+ });
129
+ socket.on("close", () => {
130
+ for (const [key, sockets] of this.waiters) {
131
+ sockets.delete(socket);
132
+ if (sockets.size === 0) {
133
+ this.waiters.delete(key);
134
+ }
135
+ }
136
+ this.signal();
137
+ });
138
+ }
139
+ // Each flag is reported once per job; every later hook gets the cached
140
+ // answer. A failed report is retried by the next call, and the hook that
141
+ // asked is refused until one lands.
142
+ report(flags, socket) {
143
+ const need = {
144
+ taint: flags.taint && !this.reported.taint,
145
+ touch: flags.touch && !this.reported.touch,
146
+ };
147
+ if (need.taint || need.touch) {
148
+ const request = this.gateway.touch(need).catch((error) => {
149
+ for (const key of ["taint", "touch"]) {
150
+ if (need[key]) {
151
+ this.reported[key] = undefined;
152
+ }
153
+ }
154
+ throw error;
155
+ });
156
+ for (const key of ["taint", "touch"]) {
157
+ if (need[key]) {
158
+ this.reported[key] = request;
159
+ }
160
+ }
161
+ }
162
+ const pending = ["taint", "touch"].flatMap((key) => flags[key] && this.reported[key]
163
+ ? [this.reported[key]]
164
+ : []);
165
+ Promise.all(pending)
166
+ .then(() => socket.end(`${JSON.stringify({ touched: true })}\n`))
167
+ .catch(() => socket.destroy());
168
+ }
169
+ async forward(ask, socket) {
170
+ try {
171
+ const { status } = await this.gateway.request(ask);
172
+ const answer = asAnswer(status);
173
+ if (answer) {
174
+ this.reply(socket, answer);
175
+ return;
176
+ }
177
+ }
178
+ catch {
179
+ // A lost lease ends the ask; an unreachable server also refuses, because a
180
+ // held call must never outlive the answer it waits for.
181
+ this.reply(socket, "expired");
182
+ return;
183
+ }
184
+ const sockets = this.waiters.get(ask.actionKey) ?? new Set();
185
+ sockets.add(socket);
186
+ this.waiters.set(ask.actionKey, sockets);
187
+ this.signal();
188
+ }
189
+ async poll() {
190
+ if (this.polling ||
191
+ this.waiters.size === 0 ||
192
+ Date.now() - this.lastPollAt < this.statusEveryMs) {
193
+ return;
194
+ }
195
+ this.polling = true;
196
+ this.lastPollAt = Date.now();
197
+ try {
198
+ const keys = [...this.waiters.keys()].slice(0, 10);
199
+ const answers = new Map((await this.gateway.status(keys)).map((row) => [
200
+ row.actionKey,
201
+ row.status,
202
+ ]));
203
+ for (const key of keys) {
204
+ const status = answers.get(key);
205
+ const answer = status === undefined ? "expired" : asAnswer(status);
206
+ if (answer) {
207
+ for (const socket of this.waiters.get(key) ?? []) {
208
+ this.reply(socket, answer);
209
+ }
210
+ this.waiters.delete(key);
211
+ }
212
+ }
213
+ }
214
+ catch (error) {
215
+ const code = error.status;
216
+ if (code === 409 || code === 404) {
217
+ for (const sockets of this.waiters.values()) {
218
+ for (const socket of sockets) {
219
+ this.reply(socket, "expired");
220
+ }
221
+ }
222
+ this.waiters.clear();
223
+ }
224
+ }
225
+ finally {
226
+ this.polling = false;
227
+ this.signal();
228
+ }
229
+ }
230
+ reply(socket, status) {
231
+ socket.end(`${JSON.stringify({ status })}\n`);
232
+ }
233
+ signal() {
234
+ const waiting = this.waiters.size > 0;
235
+ if (waiting !== this.waiting) {
236
+ this.waiting = waiting;
237
+ this.onWaiting(waiting);
238
+ }
239
+ }
240
+ }