@skrr-ai/cli 0.1.233 → 0.1.235

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.
@@ -5,9 +5,11 @@ exports.describeAgendaFailure = describeAgendaFailure;
5
5
  const core_1 = require("@oclif/core");
6
6
  const data_provider_1 = require("@skrr-ai/data-provider");
7
7
  const base_command_1 = require("../../base-command");
8
+ const agent_chat_start_1 = require("../../lib/agent-chat-start");
8
9
  const api_fetch_1 = require("../../lib/api-fetch");
9
10
  const agent_runs_1 = require("../../lib/agent-runs");
10
11
  const agentic_stream_1 = require("../../lib/agentic-stream");
12
+ const shell_quote_1 = require("../../lib/shell-quote");
11
13
  const chat_1 = require("../agents/chat");
12
14
  /**
13
15
  * The first thing a following terminal says after the runtime line. The turn is
@@ -112,11 +114,16 @@ class AgendaPlan extends base_command_1.BaseCommand {
112
114
  catch (err) {
113
115
  this.handleApiError(err);
114
116
  }
117
+ const requestRecorded = response.phase === 'request_recorded';
118
+ const admissionArgv = requestRecorded && response.clientRequestId
119
+ ? (0, agent_chat_start_1.chatAdmissionArgv)(this.config.bin, response.clientRequestId)
120
+ : undefined;
115
121
  if (flags.json) {
116
- this.log(JSON.stringify(response, null, 2));
122
+ this.log(JSON.stringify(admissionArgv
123
+ ? { ...response, admission: { argv: [...admissionArgv, '--json'] } }
124
+ : response, null, 2));
117
125
  return;
118
126
  }
119
- const requestRecorded = response.phase === 'request_recorded';
120
127
  this.log(requestRecorded
121
128
  ? `Agenda planning request recorded for agent ${args.agentId}`
122
129
  : `Agenda planning accepted for agent ${args.agentId}`);
@@ -131,8 +138,8 @@ class AgendaPlan extends base_command_1.BaseCommand {
131
138
  this.log(`Runtime: ${runtimeDescription}`);
132
139
  this.log('');
133
140
  if (!follow) {
134
- if (requestRecorded && response.clientRequestId) {
135
- this.log(`Check Run acceptance with: ${this.config.bin} runs admission ${response.clientRequestId}`);
141
+ if (admissionArgv) {
142
+ this.log(`Check Run acceptance with: ${(0, shell_quote_1.shellQuoteArgv)(admissionArgv)}`);
136
143
  }
137
144
  else {
138
145
  this.log(`Follow progress in conversation ${response.conversationId}.`);
@@ -301,6 +301,7 @@ export default class AgentsChat extends BaseCommand {
301
301
  jsonl: import("@oclif/core/interfaces").BooleanFlag<boolean>;
302
302
  json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
303
303
  'idempotency-key': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
304
+ 'idempotency-key-encoded': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
304
305
  'after-current': import("@oclif/core/interfaces").BooleanFlag<boolean>;
305
306
  'wait-for-idle': import("@oclif/core/interfaces").BooleanFlag<boolean>;
306
307
  'wait-timeout': import("@oclif/core/interfaces").OptionFlag<number | undefined, import("@oclif/core/interfaces").CustomOptions>;
@@ -35,6 +35,7 @@ const web_url_1 = require("../../lib/web-url");
35
35
  const agent_chat_queue_1 = require("../../lib/agent-chat-queue");
36
36
  const inbound_messages_1 = require("../../lib/inbound-messages");
37
37
  const cloud_reply_1 = require("../../lib/cloud-reply");
38
+ const http_error_1 = require("../../lib/http-error");
38
39
  const keychain_1 = require("../../lib/keychain");
39
40
  const local_skills_1 = require("../../lib/local-skills");
40
41
  const shell_quote_1 = require("../../lib/shell-quote");
@@ -551,6 +552,7 @@ class AgentsChat extends base_command_1.BaseCommand {
551
552
  description: 'Emit one JSON event per line while streaming. Every line is a complete JSON value. ' +
552
553
  'When the accepted Run has a source scope, run.accepted and run.detached include inspection.argv for an exact read. ' +
553
554
  'When idempotencyKey is present, use it with the original command in the same scope to reopen its reply. ' +
555
+ 'If the start cannot be confirmed, run.admission_unconfirmed includes a read-only admission.argv. ' +
554
556
  'Assistant text arrives as `text.delta`, a real delta: `delta` is the characters it ' +
555
557
  'adds, and a rewrite that is not an append arrives as `replace`, the new full text. ' +
556
558
  'Fold `text.delta` for live progress. On `text.reset`, clear the previous attempt. ' +
@@ -599,6 +601,7 @@ class AgentsChat extends base_command_1.BaseCommand {
599
601
  description: 'Emit the final one-shot response as JSON (use with --no-stream)',
600
602
  }),
601
603
  'idempotency-key': core_1.Flags.string({
604
+ exclusive: ['idempotency-key-encoded'],
602
605
  description: 'Name this start (' +
603
606
  agent_chat_start_1.START_KEY_RULE +
604
607
  '). The CLI already names every start and, when ' +
@@ -607,6 +610,10 @@ class AgentsChat extends base_command_1.BaseCommand {
607
610
  'second one. Pass your own key to re-attach to a start from another process: the same ' +
608
611
  'key and prompt return the original turn; a different prompt under it is refused.',
609
612
  }),
613
+ 'idempotency-key-encoded': core_1.Flags.string({
614
+ description: 'A URL-encoded idempotency key from a Chat reattach command.',
615
+ parse: agent_chat_start_1.decodeChatIdempotencyKey,
616
+ }),
610
617
  'after-current': core_1.Flags.boolean({
611
618
  description: 'Send this message for after the agent finishes what it is doing, instead of letting ' +
612
619
  'it reach the work in progress. The message is kept on the server at once and starts ' +
@@ -1283,7 +1290,7 @@ class AgentsChat extends base_command_1.BaseCommand {
1283
1290
  // could only report a failure and leave it running, holding balance, with its permission
1284
1291
  // prompts unanswerable (OSK-22631). With one, the same request can be sent again and the
1285
1292
  // server returns the original acceptance.
1286
- const suppliedStartKey = flags['idempotency-key'];
1293
+ const suppliedStartKey = flags['idempotency-key'] ?? flags['idempotency-key-encoded'];
1287
1294
  if (suppliedStartKey !== undefined && !(0, agent_chat_start_1.isValidStartKey)(suppliedStartKey)) {
1288
1295
  this.error(`--idempotency-key must be ${agent_chat_start_1.START_KEY_RULE}.`, { exit: 2 });
1289
1296
  }
@@ -1401,10 +1408,33 @@ class AgentsChat extends base_command_1.BaseCommand {
1401
1408
  details: busy.details,
1402
1409
  });
1403
1410
  }
1404
- if (err instanceof agent_chat_start_1.StartNotConfirmed) {
1405
- this.warn(`Check the original request with: ${this.config.bin} runs admission ${startKey}\n` +
1406
- (0, agent_chat_start_1.startNotConfirmedHint)(startKey, err.attempts));
1407
- this.handleApiError(err.lastError);
1411
+ const exhaustedReplay = err instanceof agent_chat_start_1.StartNotConfirmed;
1412
+ if (exhaustedReplay || (0, agent_chat_start_1.isUnconfirmedChatEnqueue)(err, startKey)) {
1413
+ const argv = (0, agent_chat_start_1.chatAdmissionArgv)(this.config.bin, startKey);
1414
+ const details = {
1415
+ outcome: 'unknown',
1416
+ idempotencyKey: startKey,
1417
+ ...(exhaustedReplay ? { attempts: err.attempts } : {}),
1418
+ admission: { argv: [...argv, '--json'] },
1419
+ };
1420
+ const summary = exhaustedReplay
1421
+ ? (0, agent_chat_start_1.startNotConfirmedHint)(startKey, err.attempts)
1422
+ : 'The server could not confirm whether this Chat request was accepted. Check the original request before sending another message.';
1423
+ const cause = exhaustedReplay ? err.lastError : err;
1424
+ const rawRequestId = cause?.requestId;
1425
+ const requestId = typeof rawRequestId === 'string' ? rawRequestId : undefined;
1426
+ const failure = {
1427
+ code: 'CHAT_ADMISSION_OUTCOME_UNKNOWN',
1428
+ status: (0, http_error_1.httpStatusOf)(cause),
1429
+ requestId,
1430
+ retryable: false,
1431
+ message: `${summary}\n → ${(0, shell_quote_1.shellQuoteArgv)(argv)}`,
1432
+ };
1433
+ if (flags.jsonl) {
1434
+ (0, agentic_stream_1.writeJsonLine)(process.stdout, { type: 'run.admission_unconfirmed', ...failure, ...details });
1435
+ this.exit(5);
1436
+ }
1437
+ this.failWithCliError({ ...failure, exit: 5, details });
1408
1438
  }
1409
1439
  // A refused start was the one API error on this command that escaped
1410
1440
  // `handleApiError`: it fell through to the generic catch, which printed
@@ -1464,7 +1494,7 @@ class AgentsChat extends base_command_1.BaseCommand {
1464
1494
  };
1465
1495
  const reconnectHint = recovery.idempotencyKey
1466
1496
  ? '\nTo reattach in the same workspace and profile, repeat the original command with this option:\n' +
1467
- `--idempotency-key ${(0, shell_quote_1.shellQuoteArg)(recovery.idempotencyKey)}`
1497
+ (0, shell_quote_1.shellQuoteArg)((0, agent_chat_start_1.chatIdempotencyKeyArg)(recovery.idempotencyKey))
1468
1498
  : '';
1469
1499
  if (flags.jsonl) {
1470
1500
  // Written through the one JSONL helper, not `this.log`: oclif routes that
@@ -3,9 +3,11 @@ export default class RunsAdmission extends BaseCommand {
3
3
  static description: string;
4
4
  static examples: string[];
5
5
  static args: {
6
- clientRequestId: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
6
+ clientRequestId: import("@oclif/core/interfaces").Arg<string | undefined, Record<string, unknown>>;
7
7
  };
8
8
  static flags: {
9
+ 'idempotency-key-encoded': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
+ 'ignore-workspace': import("@oclif/core/interfaces").BooleanFlag<boolean>;
9
11
  json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
10
12
  };
11
13
  run(): Promise<void>;
@@ -1,11 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const auth_core_1 = require("@skrr-ai/auth-core");
3
4
  const core_1 = require("@oclif/core");
4
5
  const base_command_1 = require("../../base-command");
5
6
  const agent_chat_start_1 = require("../../lib/agent-chat-start");
6
7
  const agent_runs_1 = require("../../lib/agent-runs");
7
8
  const api_fetch_1 = require("../../lib/api-fetch");
8
9
  const format_1 = require("../../lib/format");
10
+ const keychain_1 = require("../../lib/keychain");
11
+ const shell_quote_1 = require("../../lib/shell-quote");
9
12
  class RunsAdmission extends base_command_1.BaseCommand {
10
13
  static description = 'Check whether a recorded Chat request has an Agent Run';
11
14
  static examples = [
@@ -14,29 +17,51 @@ class RunsAdmission extends base_command_1.BaseCommand {
14
17
  ];
15
18
  static args = {
16
19
  clientRequestId: core_1.Args.string({
17
- description: 'The Chat clientRequestId or --idempotency-key',
18
- required: true,
20
+ description: 'The Chat clientRequestId',
19
21
  ignoreStdin: true,
20
- parse: async (key) => {
21
- if (!(0, agent_chat_start_1.isValidStartKey)(key))
22
- throw new Error(`Expected ${agent_chat_start_1.START_KEY_RULE}.`);
23
- return key;
24
- },
25
22
  }),
26
23
  };
27
- static flags = { json: core_1.Flags.boolean({ description: 'Output as JSON' }) };
24
+ static flags = {
25
+ 'idempotency-key-encoded': core_1.Flags.string({
26
+ description: 'A URL-encoded Chat request key from a recovery command.',
27
+ parse: agent_chat_start_1.decodeChatIdempotencyKey,
28
+ }),
29
+ 'ignore-workspace': core_1.Flags.boolean({
30
+ description: 'Look up the original authorized request without using the selected workspace.',
31
+ exclusive: ['workspace'],
32
+ }),
33
+ json: core_1.Flags.boolean({ description: 'Output as JSON' }),
34
+ };
28
35
  async run() {
29
36
  this.requireAuth();
30
- const { args: { clientRequestId }, flags } = await this.parse(RunsAdmission);
37
+ const { args, flags } = await this.parse(RunsAdmission);
38
+ const optionKey = flags['idempotency-key-encoded'];
39
+ const clientRequestId = args.clientRequestId ?? optionKey;
40
+ if (clientRequestId === undefined || (args.clientRequestId !== undefined && optionKey !== undefined)) {
41
+ this.error('Specify one Chat request key using the argument or --idempotency-key-encoded.', { exit: 2 });
42
+ }
43
+ if (!(0, agent_chat_start_1.isValidStartKey)(clientRequestId)) {
44
+ this.error(`Expected ${agent_chat_start_1.START_KEY_RULE}.`, { exit: 2 });
45
+ }
31
46
  try {
32
- const receipt = await (0, api_fetch_1.apiFetch)('/api/agentic/chat/admission?clientRequestId=' + encodeURIComponent(clientRequestId));
47
+ const receipt = await (0, api_fetch_1.apiFetch)('/api/agentic/chat/admission?clientRequestId=' + encodeURIComponent(clientRequestId), flags['ignore-workspace'] ? { workspaceScope: 'personal' } : undefined);
33
48
  if (receipt?.clientRequestId !== clientRequestId ||
34
49
  (receipt.phase === 'run_accepted' &&
35
50
  (!(0, agent_runs_1.canonicalRunId)(receipt.runId) || !Number.isFinite(Date.parse(receipt.acceptedAt))))) {
36
51
  throw new Error('Chat admission did not match the requested receipt.');
37
52
  }
53
+ let inspect;
54
+ if (receipt.phase === 'run_accepted') {
55
+ const workspace = receipt.runHistoryWorkspaceId;
56
+ if (workspace === null || (typeof workspace === 'string' && workspace.trim())) {
57
+ inspect = [
58
+ this.config.bin, 'runs', 'show', receipt.runId, ...(0, agent_runs_1.runReadScopeArgs)(workspace ?? undefined),
59
+ ...(0, auth_core_1.explicitProfileArgs)((0, keychain_1.profileForChildProcess)()),
60
+ ];
61
+ }
62
+ }
38
63
  if (flags.json) {
39
- this.log(JSON.stringify(receipt, null, 2));
64
+ this.log(JSON.stringify(inspect ? { ...receipt, inspection: { argv: [...inspect, '--json'] } } : receipt, null, 2));
40
65
  return;
41
66
  }
42
67
  switch (receipt.phase) {
@@ -46,6 +71,8 @@ class RunsAdmission extends base_command_1.BaseCommand {
46
71
  this.log(`Conversation: ${receipt.conversationId}`);
47
72
  if (receipt.dispatchPending)
48
73
  this.log('Waiting for dispatch.');
74
+ if (inspect)
75
+ this.log(`Inspect: ${(0, shell_quote_1.shellQuoteArgv)(inspect)}`);
49
76
  break;
50
77
  case 'request_recorded':
51
78
  this.log('Chat request recorded. Waiting for Run acceptance.');
@@ -10,15 +10,20 @@ const execution_history_1 = require("../../lib/execution-history");
10
10
  const format_1 = require("../../lib/format");
11
11
  const http_error_1 = require("../../lib/http-error");
12
12
  const keychain_1 = require("../../lib/keychain");
13
+ const prompt_1 = require("../../lib/prompt");
13
14
  const search_display_1 = require("../../lib/search-display");
14
15
  const shell_quote_1 = require("../../lib/shell-quote");
16
+ const workspace_header_1 = require("../../lib/workspace-header");
15
17
  class RunsList extends base_command_1.BaseCommand {
16
18
  static autonomousCredentialPolicy = 'bound-session';
17
19
  static description = 'List Agent Runs you can discover in Run History.\n\n' +
18
- 'When signed in, select an Agent, a Goal, a Chat or native conversation you own, or Hosted Jobs. ' +
20
+ 'Run without a selector in a terminal to choose an Agent. The picker uses the selected workspace, ' +
21
+ '--personal, or the Agent’s home workspace when no workspace is selected. ' +
22
+ 'For scripts, specify --agent, --goal, --conversation with --source chat or native, or --source hosted_job. ' +
19
23
  'Use --from and --to for an absolute date range.\n\n' +
20
24
  'In a bound Agent session, the session supplies the scope and supports relative ranges with --since.';
21
25
  static examples = [
26
+ '<%= config.bin %> runs list',
22
27
  '<%= config.bin %> runs list --agent <agent-id>',
23
28
  '<%= config.bin %> runs list --agent <agent-id> --source duty --json',
24
29
  '<%= config.bin %> runs list --agent <agent-id> --from 2026-12-01T00:00:00Z --status failed',
@@ -56,9 +61,11 @@ class RunsList extends base_command_1.BaseCommand {
56
61
  async run() {
57
62
  const { flags } = await this.parse(RunsList);
58
63
  const session = (0, communication_history_1.resolveHistorySession)(() => this.requireAuth());
59
- const { agent, conversation, goal, evaluation, from, to, status, cursor, limit, since, timezone, task, personal } = flags;
64
+ const { conversation, goal, evaluation, from, to, status, cursor, limit, since, timezone, task, personal } = flags;
65
+ let agent = flags.agent;
60
66
  const goalScope = goal !== undefined;
61
67
  const source = flags.source ?? (goalScope ? 'goal_planner' : undefined);
68
+ const discover = !session && [agent, conversation, goal, source, evaluation, cursor].every((value) => value === undefined);
62
69
  const conversationScope = source === 'native' || (source === 'chat' && conversation);
63
70
  const validScope = goalScope ? Boolean(goal) && source === 'goal_planner' && !agent && !conversation :
64
71
  conversationScope ? conversation && !agent :
@@ -66,7 +73,7 @@ class RunsList extends base_command_1.BaseCommand {
66
73
  const privateSource = source === 'store_trial' || source === 'release_evaluation';
67
74
  const validEvaluation = source === 'release_evaluation' ? Boolean(evaluation) : evaluation === undefined;
68
75
  if ((session && (agent || conversation || goalScope || evaluation || privateSource || personal)) ||
69
- (!session && (!validScope || !validEvaluation || since || timezone || task))) {
76
+ (!session && ((!validScope && !discover) || !validEvaluation || since || timezone || task))) {
70
77
  this.failWithCliError({
71
78
  code: 'INVALID_RUN_HISTORY_SCOPE',
72
79
  message: session && personal
@@ -78,14 +85,82 @@ class RunsList extends base_command_1.BaseCommand {
78
85
  retryable: false,
79
86
  });
80
87
  }
81
- const listArgv = (workspaceId, pageCursor) => [
88
+ const profile = (0, auth_core_1.explicitProfileArgs)((0, keychain_1.profileForChildProcess)());
89
+ const listArgv = (workspaceId, pageCursor, selection = { agent, source: flags.source }, pinScope = true) => [
82
90
  this.config.bin, 'runs', 'list',
83
- ...Object.entries({ agent, conversation, goal, source: flags.source, evaluation, from, to, status, limit })
91
+ ...Object.entries({ agent: selection.agent, conversation, goal, source: selection.source, evaluation, from, to, status, limit })
84
92
  .flatMap(([name, value]) => value === undefined ? [] : [`--${name}`, String(value)]),
85
93
  ...(pageCursor === undefined ? [] : [`--cursor=${pageCursor}`]),
86
- ...(0, agent_runs_1.runReadScopeArgs)(workspaceId),
87
- ...(0, auth_core_1.explicitProfileArgs)((0, keychain_1.profileForChildProcess)()),
94
+ ...(pinScope ? (0, agent_runs_1.runReadScopeArgs)(workspaceId) : []),
95
+ ...profile,
88
96
  ];
97
+ let chosen;
98
+ if (discover) {
99
+ const workspaceId = personal ? undefined : (0, workspace_header_1.withWorkspaceHeader)({})['X-Workspace-Id'];
100
+ const json = this.wantsJsonOutput();
101
+ const interactive = !json && process.stdin.isTTY && process.stdout.isTTY && process.stderr.isTTY;
102
+ let rosterCursor;
103
+ for (;;) {
104
+ let page;
105
+ try {
106
+ page = await (0, agent_runs_1.discoverAgentRunScopes)({ workspaceId, personal: Boolean(personal), cursor: rosterCursor });
107
+ }
108
+ catch (error) {
109
+ this.handleApiError(error);
110
+ }
111
+ if (interactive && (page.choices.length || page.nextCursor)) {
112
+ this.logToStderr('Choose an Agent to view its Run History.');
113
+ page.choices.forEach((choice, index) => {
114
+ const name = (0, search_display_1.searchDisplayText)(choice.name ?? '') || choice.id;
115
+ const scope = choice.workspaceId ? `workspace ${choice.workspaceId}` : 'personal';
116
+ this.logToStderr(` ${index + 1}. ${name} (${choice.id} · ${scope})`);
117
+ });
118
+ const answer = await (0, prompt_1.prompt)(page.nextCursor ? 'Number, m for more, or Enter to cancel: ' :
119
+ 'Number or Enter to cancel: ', { output: process.stderr });
120
+ if (!answer)
121
+ return;
122
+ if (answer.toLowerCase() === 'm' && page.nextCursor) {
123
+ rosterCursor = page.nextCursor;
124
+ continue;
125
+ }
126
+ chosen = /^[1-9][0-9]*$/.test(answer) ? page.choices[Number(answer) - 1] : undefined;
127
+ if (!chosen)
128
+ this.failWithCliError({
129
+ code: 'INVALID_RUN_HISTORY_AGENT_SELECTION', message: 'Choose a number from the Agent list.',
130
+ exit: 1, retryable: false,
131
+ });
132
+ agent = chosen.id;
133
+ break;
134
+ }
135
+ const command = (argv) => ({ argv, command: (0, shell_quote_1.shellQuoteArgv)(argv) });
136
+ const format = json ? ['--json'] : [];
137
+ const choices = page.choices.map(({ id, name, workspaceId }) => ({
138
+ agentId: id, name: (0, search_display_1.searchDisplayText)(name ?? '') || id, workspaceId: workspaceId ?? null,
139
+ ...command([...listArgv(workspaceId, undefined, { agent: id, source: undefined }), ...format]),
140
+ }));
141
+ const chooseInTerminal = command(listArgv(workspaceId, undefined, undefined, Boolean(workspaceId || personal)));
142
+ const hosted = command([...listArgv(workspaceId, undefined, { agent: undefined, source: 'hosted_job' }), ...format]);
143
+ // `agents list` follows the saved workspace. It has no personal override.
144
+ const browseAgents = personal ? undefined : command([
145
+ this.config.bin, 'agents', 'list', '--limit', '20',
146
+ ...(workspaceId ? ['--workspace', workspaceId] : []), ...profile, ...format,
147
+ ]);
148
+ const hints = choices.length
149
+ ? [`Select a Run History scope with --agent, or use the terminal picker.`, ` → ${choices[0].command}`]
150
+ : ['No Agents were found on this roster page.'];
151
+ if (page.nextCursor)
152
+ hints.push(`More Agents are available in the terminal picker.\n → ${chooseInTerminal.command}`);
153
+ if (browseAgents)
154
+ hints.push(`Browse Agents and use --q to search by name.\n → ${browseAgents.command}`);
155
+ if (!choices.length)
156
+ hints.push(`View Hosted Job history.\n → ${hosted.command}`);
157
+ this.failWithCliError({
158
+ code: 'RUN_HISTORY_SCOPE_REQUIRED', message: hints.join('\n'), exit: 1, retryable: false,
159
+ details: { choices, hasMoreAgents: Boolean(page.nextCursor), chooseInTerminal, hosted,
160
+ ...(browseAgents ? { browseAgents } : {}) },
161
+ });
162
+ }
163
+ }
89
164
  try {
90
165
  const { page, workspaceId } = session ? {
91
166
  page: await (0, execution_history_1.readExecutionHistory)(session.sessionId, 'list', {
@@ -94,7 +169,8 @@ class RunsList extends base_command_1.BaseCommand {
94
169
  workspaceId: undefined,
95
170
  } : await (0, agent_runs_1.listAgentRuns)({
96
171
  agentId: agent, conversationId: conversation, goalId: goal,
97
- source, evaluationId: evaluation, from, to, status, cursor, limit, personal,
172
+ source, evaluationId: evaluation, from, to, status, cursor, limit,
173
+ personal: chosen ? !chosen.workspaceId : personal, workspaceId: chosen?.workspaceId,
98
174
  });
99
175
  const continuation = !session && page.nextCursor ? listArgv(workspaceId, page.nextCursor) : undefined;
100
176
  if (flags.json) {
@@ -38,11 +38,18 @@ export declare const START_KEY_RULE = "1-128 characters: letters, numbers, dot,
38
38
  export declare const DEFAULT_REPLAY_DELAYS_MS: readonly number[];
39
39
  /** A fresh key for one invocation. Reused by every replay of that invocation, never across them. */
40
40
  export declare function newStartKey(): string;
41
+ /** Keep caller-supplied keys such as --help inside one option value. */
42
+ export declare function chatIdempotencyKeyArg(key: string): string;
43
+ export declare function decodeChatIdempotencyKey(encoded: string): Promise<string>;
44
+ /** Preserve the deployment and requested workspace of an earlier Chat start. */
45
+ export declare function chatAdmissionArgv(bin: string, clientRequestId: string): string[];
41
46
  /** Whether a caller-supplied key is one the server will accept. */
42
47
  export declare function isValidStartKey(value: string): boolean;
43
48
  export type StartVerdict = 'replay' | 'surface';
44
49
  interface ErrorBody {
45
50
  errorType?: unknown;
51
+ clientRequestId?: unknown;
52
+ inspectConversationBeforeRetry?: unknown;
46
53
  retryable?: unknown;
47
54
  code?: unknown;
48
55
  message?: unknown;
@@ -51,6 +58,8 @@ interface ErrorBody {
51
58
  export declare const CONVERSATION_BUSY = "conversation_busy";
52
59
  /** The JSON body of a failed response, when the transport kept it as text or as an object. */
53
60
  export declare function bodyOf(err: unknown): ErrorBody | undefined;
61
+ /** A terminal server reply for this exact direct start. Read its receipt without replaying the POST. */
62
+ export declare function isUnconfirmedChatEnqueue(err: unknown, clientRequestId: string): boolean;
54
63
  /**
55
64
  * Whether a failed start may be sent again under the same key.
56
65
  *
@@ -33,8 +33,12 @@
33
33
  Object.defineProperty(exports, "__esModule", { value: true });
34
34
  exports.StartNotConfirmed = exports.ConversationStillBusy = exports.DEFAULT_BUSY_WAIT_DELAYS_MS = exports.DEFAULT_WAIT_FOR_IDLE_TIMEOUT_MS = exports.CONVERSATION_BUSY = exports.DEFAULT_REPLAY_DELAYS_MS = exports.START_KEY_RULE = void 0;
35
35
  exports.newStartKey = newStartKey;
36
+ exports.chatIdempotencyKeyArg = chatIdempotencyKeyArg;
37
+ exports.decodeChatIdempotencyKey = decodeChatIdempotencyKey;
38
+ exports.chatAdmissionArgv = chatAdmissionArgv;
36
39
  exports.isValidStartKey = isValidStartKey;
37
40
  exports.bodyOf = bodyOf;
41
+ exports.isUnconfirmedChatEnqueue = isUnconfirmedChatEnqueue;
38
42
  exports.classifyStartFailure = classifyStartFailure;
39
43
  exports.isConversationBusy = isConversationBusy;
40
44
  exports.startWithReplay = startWithReplay;
@@ -43,7 +47,10 @@ exports.busyStartFailure = busyStartFailure;
43
47
  exports.busyWaitNotice = busyWaitNotice;
44
48
  exports.startNotConfirmedHint = startNotConfirmedHint;
45
49
  const node_crypto_1 = require("node:crypto");
50
+ const auth_core_1 = require("@skrr-ai/auth-core");
46
51
  const http_error_1 = require("./http-error");
52
+ const keychain_1 = require("./keychain");
53
+ const workspace_header_1 = require("./workspace-header");
47
54
  const IS_NETWORK_FAILURE_RE = /fetch failed|socket hang up/i;
48
55
  /** The server accepts 1-128 characters: letters, numbers, dot, underscore, colon, hyphen. */
49
56
  const START_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
@@ -58,6 +65,26 @@ exports.DEFAULT_REPLAY_DELAYS_MS = [2_000, 4_000, 8_000, 15_000, 15_000];
58
65
  function newStartKey() {
59
66
  return `cli-chat:${(0, node_crypto_1.randomUUID)()}`;
60
67
  }
68
+ /** Keep caller-supplied keys such as --help inside one option value. */
69
+ function chatIdempotencyKeyArg(key) {
70
+ // oclif also rejects a recognized flag inside an equals-form option value.
71
+ return `--idempotency-key-encoded=${encodeURIComponent(key).replace(/^-/, '%2D')}`;
72
+ }
73
+ async function decodeChatIdempotencyKey(encoded) {
74
+ const key = decodeURIComponent(encoded);
75
+ if (!isValidStartKey(key))
76
+ throw new Error(`Expected ${exports.START_KEY_RULE}.`);
77
+ return key;
78
+ }
79
+ /** Preserve the deployment and requested workspace of an earlier Chat start. */
80
+ function chatAdmissionArgv(bin, clientRequestId) {
81
+ const workspaceId = (0, workspace_header_1.withWorkspaceHeader)({})['X-Workspace-Id'];
82
+ return [
83
+ bin, 'runs', 'admission', chatIdempotencyKeyArg(clientRequestId),
84
+ ...(workspaceId ? ['--workspace', workspaceId] : ['--ignore-workspace']),
85
+ ...(0, auth_core_1.explicitProfileArgs)((0, keychain_1.profileForChildProcess)()),
86
+ ];
87
+ }
61
88
  /** Whether a caller-supplied key is one the server will accept. */
62
89
  function isValidStartKey(value) {
63
90
  return START_KEY_PATTERN.test(value);
@@ -81,6 +108,16 @@ function bodyOf(err) {
81
108
  return undefined;
82
109
  }
83
110
  }
111
+ /** A terminal server reply for this exact direct start. Read its receipt without replaying the POST. */
112
+ function isUnconfirmedChatEnqueue(err, clientRequestId) {
113
+ if ((0, http_error_1.httpStatusOf)(err) !== 409)
114
+ return false;
115
+ const body = bodyOf(err);
116
+ return body?.errorType === 'agentic_enqueue_outcome_unconfirmed' &&
117
+ body.code === 'ENQUEUE_OUTCOME_UNCONFIRMED' &&
118
+ body.clientRequestId === clientRequestId &&
119
+ body.inspectConversationBeforeRetry === true;
120
+ }
84
121
  const NETWORK_CODES = new Set([
85
122
  'ECONNRESET',
86
123
  'ECONNABORTED',
@@ -310,6 +347,6 @@ function busyWaitNotice(info, conversationId) {
310
347
  function startNotConfirmedHint(key, attempts) {
311
348
  return (`The server never confirmed this start after ${attempts} attempt${attempts === 1 ? '' : 's'}. ` +
312
349
  `The turn may still have been accepted and be running. Re-run the same command with ` +
313
- `--idempotency-key ${key} to attach to it if it was, or to start it once if it was not; ` +
350
+ `${chatIdempotencyKeyArg(key)} to attach to it if it was, or to start it once if it was not; ` +
314
351
  `a new key could start a second turn.`);
315
352
  }
@@ -4,11 +4,25 @@ export declare const runIdArgument: import("@oclif/core/interfaces").Arg<string,
4
4
  export declare function exactAttemptId(input: string): string;
5
5
  export declare const attemptIdFlag: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
6
6
  export declare function runReadScopeArgs(workspaceId?: string): string[];
7
+ export type AgentRunScopeChoice = {
8
+ id: string;
9
+ name?: string;
10
+ workspaceId?: string;
11
+ };
12
+ /** Discover Agents through the ordinary roster; Run History reauthorizes the selected partition. */
13
+ export declare function discoverAgentRunScopes({ workspaceId, personal, cursor }: {
14
+ workspaceId?: string;
15
+ personal: boolean;
16
+ cursor?: string;
17
+ }): Promise<{
18
+ choices: AgentRunScopeChoice[];
19
+ nextCursor?: string;
20
+ }>;
7
21
  export declare class RunListCursorInvalidError extends Error {
8
22
  readonly workspaceId: string | undefined;
9
23
  constructor(workspaceId: string | undefined, cause: unknown);
10
24
  }
11
- export declare function listAgentRuns({ agentId, conversationId, goalId, source, evaluationId, from, to, status, cursor, limit, personal, }: {
25
+ export declare function listAgentRuns({ agentId, conversationId, goalId, source, evaluationId, from, to, status, cursor, limit, personal, workspaceId, }: {
12
26
  agentId?: string;
13
27
  conversationId?: string;
14
28
  goalId?: string;
@@ -20,6 +34,7 @@ export declare function listAgentRuns({ agentId, conversationId, goalId, source,
20
34
  cursor?: string;
21
35
  limit?: number;
22
36
  personal?: boolean;
37
+ workspaceId?: string;
23
38
  }): Promise<{
24
39
  page: AgentRunHistoryPage;
25
40
  workspaceId?: string;
@@ -4,6 +4,7 @@ exports.RunStopConflictError = exports.RunStopUnconfirmedError = exports.RunTran
4
4
  exports.canonicalRunId = canonicalRunId;
5
5
  exports.exactAttemptId = exactAttemptId;
6
6
  exports.runReadScopeArgs = runReadScopeArgs;
7
+ exports.discoverAgentRunScopes = discoverAgentRunScopes;
7
8
  exports.listAgentRuns = listAgentRuns;
8
9
  exports.listPrivateReleaseEvalHistory = listPrivateReleaseEvalHistory;
9
10
  exports.chatCopyOrigin = chatCopyOrigin;
@@ -12,6 +13,7 @@ exports.readAgentRunEvents = readAgentRunEvents;
12
13
  exports.readAgentRunTranscript = readAgentRunTranscript;
13
14
  exports.stopAgentRun = stopAgentRun;
14
15
  const core_1 = require("@oclif/core");
16
+ const data_provider_1 = require("@skrr-ai/data-provider");
15
17
  const api_fetch_1 = require("./api-fetch");
16
18
  const http_error_1 = require("./http-error");
17
19
  const search_display_1 = require("./search-display");
@@ -22,6 +24,8 @@ const ATTEMPT_ID = /^aa_[A-Za-z0-9_-]{43}$/;
22
24
  const STOPPABLE = new Set(['queued', 'active', 'reconciling', 'stopping']);
23
25
  const TERMINAL = new Set(['succeeded', 'failed', 'cancelled', 'expired']);
24
26
  const RUNS_PATH = '/api/agent-runs';
27
+ const AGENT_DISCOVERY_LIMIT = 12;
28
+ const DISCOVERY_ID = /^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,199}$/;
25
29
  function canonicalRunId(value) {
26
30
  return typeof value === 'string' && RUN_ID.test(value) ? value : undefined;
27
31
  }
@@ -54,12 +58,12 @@ function path(runId) {
54
58
  function runReadScopeArgs(workspaceId) {
55
59
  return workspaceId ? ['--workspace', workspaceId] : ['--personal'];
56
60
  }
57
- async function readRunResource(endpoint, read = api_fetch_1.apiFetch, { allowDefaultWorkspace = true, personal = false } = {}) {
61
+ async function readRunResource(endpoint, read = api_fetch_1.apiFetch, { allowDefaultWorkspace = true, personal = false, workspaceId } = {}) {
58
62
  if (personal) {
59
63
  const scope = { workspaceScope: 'personal' };
60
64
  return { value: await read(endpoint, scope), scope };
61
65
  }
62
- const headers = (0, workspace_header_1.withWorkspaceHeader)({});
66
+ const headers = (0, workspace_header_1.withWorkspaceHeader)(workspaceId ? { 'X-Workspace-Id': workspaceId } : {});
63
67
  const scope = headers['X-Workspace-Id'] ? { headers } : undefined;
64
68
  try {
65
69
  return { value: await read(endpoint, scope), scope };
@@ -79,6 +83,38 @@ async function readRunResource(endpoint, read = api_fetch_1.apiFetch, { allowDef
79
83
  return { value: await read(endpoint, defaultScope), scope: defaultScope };
80
84
  }
81
85
  }
86
+ /** Discover Agents through the ordinary roster; Run History reauthorizes the selected partition. */
87
+ async function discoverAgentRunScopes({ workspaceId, personal, cursor }) {
88
+ const query = new URLSearchParams({
89
+ requiredPermission: String(data_provider_1.PermissionBits.VIEW), fields: 'summary', limit: String(AGENT_DISCOVERY_LIMIT),
90
+ ...(cursor ? { cursor } : {}),
91
+ });
92
+ const scope = workspaceId ? { headers: { 'X-Workspace-Id': workspaceId } } : { workspaceScope: 'personal' };
93
+ const page = await (0, api_fetch_1.apiFetch)(`/api/agents?${query}`, scope);
94
+ if (!Array.isArray(page?.data) || page.data.length > AGENT_DISCOVERY_LIMIT ||
95
+ typeof page.has_more !== 'boolean' ||
96
+ (page.has_more && (typeof page.after !== 'string' || !(0, search_display_1.isPrintableSearchCursor)(page.after) || page.after === cursor))) {
97
+ throw new Error('The server did not provide a valid Agent roster page.');
98
+ }
99
+ const choices = [];
100
+ for (const agent of page.data) {
101
+ if (typeof agent?.id !== 'string' || !DISCOVERY_ID.test(agent.id))
102
+ continue;
103
+ const home = agent.workspaceId;
104
+ if (home != null && (typeof home !== 'string' || !DISCOVERY_ID.test(home)))
105
+ continue;
106
+ // The roster can receive a null workspace context after a refused header.
107
+ // Its broader account view must never supply choices for that workspace.
108
+ if (workspaceId && home !== workspaceId)
109
+ continue;
110
+ choices.push({
111
+ id: agent.id,
112
+ name: typeof agent.name === 'string' ? agent.name : undefined,
113
+ workspaceId: personal ? undefined : workspaceId ?? home ?? undefined,
114
+ });
115
+ }
116
+ return { choices, nextCursor: page.has_more && typeof page.after === 'string' ? page.after : undefined };
117
+ }
82
118
  class RunListCursorInvalidError extends Error {
83
119
  workspaceId;
84
120
  constructor(workspaceId, cause) {
@@ -87,7 +123,7 @@ class RunListCursorInvalidError extends Error {
87
123
  }
88
124
  }
89
125
  exports.RunListCursorInvalidError = RunListCursorInvalidError;
90
- async function listAgentRuns({ agentId, conversationId, goalId, source, evaluationId, from, to, status, cursor, limit, personal = false, }) {
126
+ async function listAgentRuns({ agentId, conversationId, goalId, source, evaluationId, from, to, status, cursor, limit, personal = false, workspaceId, }) {
91
127
  const query = new URLSearchParams();
92
128
  for (const [key, value] of Object.entries({ agentId, conversationId, goalId, source, evaluationId, from, to, status, cursor, limit })) {
93
129
  if (value !== undefined)
@@ -104,7 +140,7 @@ async function listAgentRuns({ agentId, conversationId, goalId, source, evaluati
104
140
  }
105
141
  throw error;
106
142
  }
107
- }, { allowDefaultWorkspace: cursor === undefined, personal });
143
+ }, { allowDefaultWorkspace: cursor === undefined, personal, workspaceId });
108
144
  if (!Array.isArray(value?.items) ||
109
145
  !value.items.every((row) => canonicalRunId(row?.id) && typeof row.source === 'string' &&
110
146
  typeof row.status === 'string' && typeof row.acceptedAt === 'string' &&