@sequenceholdings/studio-cli 0.5.4 → 0.6.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 (54) hide show
  1. package/README.md +226 -7
  2. package/dist/agents/source.js +2 -1
  3. package/dist/app/adapters.js +2 -1
  4. package/dist/app/commands.js +4 -4
  5. package/dist/artifact/delegate.js +32 -12
  6. package/dist/atlas-client.d.ts +2 -1
  7. package/dist/atlas-client.js +7 -3
  8. package/dist/auth-cmds/commands.d.ts +1 -1
  9. package/dist/auth-cmds/commands.js +3 -0
  10. package/dist/auth.d.ts +2 -1
  11. package/dist/auth.js +16 -0
  12. package/dist/command-contract.d.ts +8 -8
  13. package/dist/command-contract.js +6 -6
  14. package/dist/command-help.d.ts +5 -4
  15. package/dist/command-help.js +41 -4
  16. package/dist/command-input.js +2 -2
  17. package/dist/config.d.ts +5 -0
  18. package/dist/config.js +14 -1
  19. package/dist/env-flags.d.ts +6 -0
  20. package/dist/env-flags.js +9 -0
  21. package/dist/functions/commands.d.ts +4 -1
  22. package/dist/functions/commands.js +63 -5
  23. package/dist/functions/deploy-preflight.js +2 -2
  24. package/dist/functions/manifest.d.ts +43 -29
  25. package/dist/functions/manifest.js +37 -74
  26. package/dist/main.js +42 -2
  27. package/dist/orm/delegate.js +25 -4
  28. package/dist/orm/read.d.ts +54 -0
  29. package/dist/orm/read.js +308 -0
  30. package/dist/pipeline/commands.js +30 -5
  31. package/dist/pipeline/discovery.js +3 -16
  32. package/dist/pipeline/lifecycle.js +37 -6
  33. package/dist/pipeline/retirement.d.ts +3 -0
  34. package/dist/pipeline/retirement.js +34 -0
  35. package/dist/pipeline/source.d.ts +21 -0
  36. package/dist/pipeline/source.js +76 -0
  37. package/dist/process/build.js +4 -0
  38. package/dist/process/codegen.js +2 -0
  39. package/dist/process/commands.js +57 -18
  40. package/dist/process/plan-diff.js +1 -0
  41. package/dist/process/runs.d.ts +14 -0
  42. package/dist/process/runs.js +238 -0
  43. package/dist/repos/ci-status.js +28 -0
  44. package/dist/repos/commands.js +11 -1
  45. package/dist/repos/git-credential.d.ts +3 -2
  46. package/dist/repos/git-credential.js +52 -3
  47. package/dist/repos/pulls.d.ts +7 -1
  48. package/dist/repos/pulls.js +162 -22
  49. package/dist/sandbox-auth.d.ts +52 -0
  50. package/dist/sandbox-auth.js +105 -0
  51. package/dist/storage/commands.js +6 -5
  52. package/dist/text-table.d.ts +7 -0
  53. package/dist/text-table.js +16 -0
  54. package/package.json +9 -9
@@ -0,0 +1,76 @@
1
+ import { z } from 'zod';
2
+ import { resolveRepo } from '@sequenceholdings/artifact-studio/git-service-client';
3
+ import { getAccessToken } from '../auth.js';
4
+ import { resolveConfiguredEnv } from '../config.js';
5
+ export function pipelineSourceError(verb, flags) {
6
+ const source = flags['source-env'];
7
+ if (source === undefined)
8
+ return null;
9
+ if (typeof source !== 'string' || !source.trim())
10
+ return '--source-env requires a supported first-party environment name';
11
+ if (verb !== 'plan' && verb !== 'deploy') {
12
+ return '--source-env is supported only for a new plan or deploy; rollback uses retained source. To re-plan a historical source commit, use deploy --ref <sha> --source-env <env>';
13
+ }
14
+ if (['dir', 'deployment-id', 'plan-request-id', 'migration', 'in-place'].some((flag) => flags[flag] !== undefined)) {
15
+ return '--source-env cannot be combined with --dir, existing plan/deployment IDs, or coordinated migrations';
16
+ }
17
+ return null;
18
+ }
19
+ export async function resolvePipelineSource({ sourceEnvironment, repo }) {
20
+ if (!sourceEnvironment)
21
+ return {};
22
+ const match = /^([a-z][a-z0-9-]*)\/([a-z][a-z0-9-]*)(?:@(.+))?$/.exec(repo);
23
+ if (!match)
24
+ throw new Error('--repo must be <namespace>/<name>[@<root>] for --source-env');
25
+ const root = match[3]?.replaceAll('\\', '/');
26
+ if (root && root !== '.' && !root.split('/').every(part => /^[A-Za-z0-9._-]+$/.test(part) && part !== '.' && part !== '..')) {
27
+ throw new Error('--repo root must be a contained relative directory');
28
+ }
29
+ const source = await resolveConfiguredEnv({ requested: sourceEnvironment });
30
+ const token = await getAccessToken({ env: source.name, targetUrl: source.url });
31
+ const repository = await resolveRepo({ baseUrl: source.url, token, namespace: match[1], name: match[2] });
32
+ // The target independently checks its trusted origin registry and source read access,
33
+ // resolves the supplied ref, and stores verified bytes before queuing work.
34
+ return { sourceEnvironment: source.name, sourceRepositoryId: repository.id, sourceAuthorization: `Bearer ${token}` };
35
+ }
36
+ const sourcePlanSchema = z.object({
37
+ repo: z.string(),
38
+ ref: z.string(),
39
+ commit: z.string().regex(/^[a-f0-9]{40}$/),
40
+ environment: z.string(),
41
+ sourceSnapshot: z.object({
42
+ version: z.literal(1),
43
+ repo: z.string(),
44
+ sourceEnvironment: z.string(),
45
+ sourceRepositoryId: z.string(),
46
+ commit: z.string().regex(/^[a-f0-9]{40}$/),
47
+ digest: z.string().regex(/^[a-f0-9]{64}$/),
48
+ bytes: z.number().int().positive(),
49
+ fileCount: z.number().int().nonnegative(),
50
+ }),
51
+ });
52
+ /** Older target APIs can silently strip source fields. Never use their local plan. */
53
+ export function assertPipelineSourcePlan({ plan, request }) {
54
+ if (!request.sourceEnvironment)
55
+ return;
56
+ const parsed = sourcePlanSchema.safeParse(plan);
57
+ const [baseRepo, embeddedRoot] = request.repo.split('@');
58
+ const root = (embeddedRoot ?? request.root)?.replaceAll('\\', '/');
59
+ const repo = root && root !== '.' ? `${baseRepo}@${root}` : baseRepo;
60
+ if (parsed.success) {
61
+ const receipt = parsed.data.sourceSnapshot;
62
+ if (receipt.sourceEnvironment === request.sourceEnvironment
63
+ && receipt.sourceRepositoryId === request.sourceRepositoryId
64
+ && receipt.repo === repo
65
+ && parsed.data.repo === repo
66
+ && parsed.data.environment === request.environment
67
+ && parsed.data.ref === request.ref
68
+ && receipt.commit === parsed.data.commit
69
+ && (!/^[a-f0-9]{40}$/i.test(request.ref) || receipt.commit === request.ref.toLowerCase())) {
70
+ return;
71
+ }
72
+ }
73
+ throw new Error('The target returned no matching source snapshot for the requested pipeline source. ' +
74
+ 'Refusing credential attachment or deployment. Verify the target supports --source-env ' +
75
+ 'and retry planning after its API and source workers are fully rolled out.');
76
+ }
@@ -197,6 +197,8 @@ function serializeNodeMetadata(node) {
197
197
  meta.output_mode = agent.outputMode;
198
198
  if (agent.workflowId !== undefined)
199
199
  meta.workflow_id = agent.workflowId;
200
+ if (agent.expectedIdentity !== undefined)
201
+ meta.expected_identity = { ...agent.expectedIdentity };
200
202
  if (agent.on_reset_edge_id)
201
203
  meta.on_reset_edge_id = agent.on_reset_edge_id;
202
204
  if (agent.bindings)
@@ -316,6 +318,8 @@ function serializeNodeMetadata(node) {
316
318
  ? { join_source: parallel.join.toString() }
317
319
  : { join_expr: parallel.join.expr }),
318
320
  };
321
+ if (parallel.captureProvenance === true)
322
+ pmeta.capture_provenance = true;
319
323
  // Serialized only when non-default ('eager') so existing barrier
320
324
  // bundles keep their hashes; a missing field reads as 'barrier'.
321
325
  if (parallel.join_mode === 'eager') {
@@ -105,6 +105,7 @@ function emitNode(node, ctx) {
105
105
  m.allowed_tools !== undefined ? ` allowedTools: ${JSON.stringify(m.allowed_tools)},` : null,
106
106
  m.output_mode !== undefined ? ` outputMode: ${value(m.output_mode)},` : null,
107
107
  m.workflow_id != null ? ` workflowId: ${lit(String(m.workflow_id))},` : null,
108
+ m.expected_identity !== undefined ? ` expectedIdentity: ${JSON.stringify(m.expected_identity)},` : null,
108
109
  m.on_reset_edge_id != null ? ` on_reset_edge_id: ${lit(String(m.on_reset_edge_id))},` : null,
109
110
  m.timeout !== undefined ? ` timeout: ${value(m.timeout)},` : null,
110
111
  bindings(m.bindings),
@@ -194,6 +195,7 @@ function emitNode(node, ctx) {
194
195
  ...head,
195
196
  ...branchFields,
196
197
  par.max_concurrency !== undefined ? ` max_concurrency: ${par.max_concurrency},` : null,
198
+ par.capture_provenance === true ? ` captureProvenance: true,` : null,
197
199
  par.supervisor_retry !== undefined
198
200
  ? ` supervisor_retry: ${retryConfig(par.supervisor_retry, ctx)},`
199
201
  : null,
@@ -12,6 +12,7 @@ import { fileURLToPath } from 'node:url';
12
12
  import { forEachSerializedNode, } from '@sequenceholdings/lattice/bundle';
13
13
  import { getJson, getJsonOr404, postJson, AtlasApiError } from '../atlas-client.js';
14
14
  import { generateProcessFiles } from './codegen.js';
15
+ import { readSandboxToken, sandboxTarget, sourceAuthMode } from '../sandbox-auth.js';
15
16
  import { getAccessToken, getAccessTokenWithMode, inspectAuthPreflight, AuthTokenStoreError, NotLoggedInError, } from '../auth.js';
16
17
  import { readConfig, resolveEnv, resolveConfiguredEnv } from '../config.js';
17
18
  import { currentVersion } from '../update-check.js';
@@ -403,7 +404,7 @@ async function applyLocal(args) {
403
404
  }
404
405
  async function applyFromRepo(args, spec) {
405
406
  const { authMode, env, token } = await getEnvAndAuth(args);
406
- const source = await resolveArtifactSource({ kind: 'git-service', namespace: spec.namespace, name: spec.name, ref: spec.ref }, { authMode, baseUrl: env.url, token });
407
+ const source = await resolveArtifactSource({ kind: 'git-service', namespace: spec.namespace, name: spec.name, ref: spec.ref }, { authMode: sourceAuthMode(authMode), baseUrl: env.url, token });
407
408
  try {
408
409
  await prepareProcessBuildRoot(source.dir);
409
410
  const compiled = await compileProcessSourceIsolated({
@@ -916,6 +917,24 @@ function doctorBooleanFlag({ key, value }) {
916
917
  return true;
917
918
  throw new Error(`--${key} accepts only true or false.`);
918
919
  }
920
+ async function sandboxAuthPreflight(sandbox) {
921
+ try {
922
+ await readSandboxToken(sandbox);
923
+ return {
924
+ ok: true,
925
+ line: `auth preflight: ok — sandbox token readable at ${sandbox.tokenFile}; login, token cache, and environment registry are not used`,
926
+ diagnostics: { status: 'sandbox', tokenFile: sandbox.tokenFile, tokenReadable: true },
927
+ };
928
+ }
929
+ catch (err) {
930
+ const detail = err instanceof Error ? err.message : String(err);
931
+ return {
932
+ ok: false,
933
+ line: `auth preflight: FAIL — ${detail}`,
934
+ diagnostics: { status: 'sandbox', tokenFile: sandbox.tokenFile, tokenReadable: false, detail },
935
+ };
936
+ }
937
+ }
919
938
  export async function doctorCommand(args) {
920
939
  if (args.flags.help || args.positional.includes('-h') || args.positional[0] === 'help') {
921
940
  console.log('usage: seq-studio doctor [-e <env>] [--json] [--offline]\n\nDiagnose configuration, authentication, local service availability, CLI/SDK resolution, and deployment access. Does not open a browser. --offline reads only local config and token metadata; it performs no discovery or HTTP requests.');
@@ -979,6 +998,17 @@ export async function doctorCommand(args) {
979
998
  lines.push(`config: ok — default_env=${config.defaultEnv}, envs=${Object.keys(config.envs).join(',')}`);
980
999
  }
981
1000
  const requested = typeof args.flags.env === 'string' ? args.flags.env : undefined;
1001
+ let sandbox = null;
1002
+ try {
1003
+ sandbox = sandboxTarget();
1004
+ if (sandbox) {
1005
+ lines.push(`sandbox: token-file mode — ${sandbox.baseUrl}, token read from ${sandbox.tokenFile} on every request; -e is ignored`);
1006
+ }
1007
+ }
1008
+ catch (err) {
1009
+ lines.push(`sandbox: FAIL — ${err instanceof Error ? err.message : String(err)}`);
1010
+ ok = false;
1011
+ }
982
1012
  let env = null;
983
1013
  if (config) {
984
1014
  try {
@@ -1010,24 +1040,33 @@ export async function doctorCommand(args) {
1010
1040
  else if (!offline && isLoopbackUrl(env.url)) {
1011
1041
  lines.push(`local service: ok — ${env.url}`);
1012
1042
  }
1013
- try {
1014
- authPreflight = await inspectAuthPreflight({
1015
- env: env.name,
1016
- offline,
1017
- ...(offline ? {} : { targetUrl: env.url }),
1018
- });
1019
- diagnostics.auth = authPreflight;
1020
- lines.push(`auth cache: ${authPreflight.tokenCache}; user token ${authPreflight.cachedUserToken}; ` +
1021
- `M2M credential ${authPreflight.m2mCredentialConfigured ? 'configured' : 'not configured'} ` +
1022
- `(mode=${authPreflight.authMode}, realm=${authPreflight.realm}${authPreflight.realmVerified ? '' : ', unverified offline'})`);
1043
+ if (sandbox) {
1044
+ // No login, token cache, or registry exists in a sandbox; inspect the token source instead.
1045
+ const result = await sandboxAuthPreflight(sandbox);
1046
+ diagnostics.auth = result.diagnostics;
1047
+ lines.push(result.line);
1048
+ ok &&= result.ok;
1023
1049
  }
1024
- catch (err) {
1025
- diagnostics.auth = {
1026
- status: 'unavailable',
1027
- detail: err instanceof Error ? err.message : String(err),
1028
- };
1029
- lines.push(`auth preflight: FAIL — ${err instanceof Error ? err.message : String(err)}`);
1030
- ok = false;
1050
+ else {
1051
+ try {
1052
+ authPreflight = await inspectAuthPreflight({
1053
+ env: env.name,
1054
+ offline,
1055
+ ...(offline ? {} : { targetUrl: env.url }),
1056
+ });
1057
+ diagnostics.auth = authPreflight;
1058
+ lines.push(`auth cache: ${authPreflight.tokenCache}; user token ${authPreflight.cachedUserToken}; ` +
1059
+ `M2M credential ${authPreflight.m2mCredentialConfigured ? 'configured' : 'not configured'} ` +
1060
+ `(mode=${authPreflight.authMode}, realm=${authPreflight.realm}${authPreflight.realmVerified ? '' : ', unverified offline'})`);
1061
+ }
1062
+ catch (err) {
1063
+ diagnostics.auth = {
1064
+ status: 'unavailable',
1065
+ detail: err instanceof Error ? err.message : String(err),
1066
+ };
1067
+ lines.push(`auth preflight: FAIL — ${err instanceof Error ? err.message : String(err)}`);
1068
+ ok = false;
1069
+ }
1031
1070
  }
1032
1071
  }
1033
1072
  try {
@@ -173,6 +173,7 @@ const BEHAVIORAL_METADATA_FIELDS = {
173
173
  ],
174
174
  agent: [
175
175
  'agent_version',
176
+ 'expected_identity',
176
177
  'allowed_tools',
177
178
  'output_mode',
178
179
  'input_mapper_source',
@@ -0,0 +1,14 @@
1
+ /**
2
+ * `seq-studio process runs <start|list|show|cancel>` — start and observe
3
+ * Lattice runs through the programmatic run API, as the caller. Starting needs
4
+ * `invoker` on the process; reading a run needs `viewer` on it.
5
+ */
6
+ import type { ParsedArgs } from './commands.js';
7
+ type Sleep = (ms: number) => Promise<void>;
8
+ /** Validate every flag before authenticating so a typo never starts a run. */
9
+ export declare function startRunBody(args: ParsedArgs): Promise<Record<string, unknown>>;
10
+ export declare function listRunsQuery(args: ParsedArgs): URLSearchParams;
11
+ export declare function processRunsCommand(args: ParsedArgs, deps?: {
12
+ sleep?: Sleep;
13
+ }): Promise<number>;
14
+ export {};
@@ -0,0 +1,238 @@
1
+ /**
2
+ * `seq-studio process runs <start|list|show|cancel>` — start and observe
3
+ * Lattice runs through the programmatic run API, as the caller. Starting needs
4
+ * `invoker` on the process; reading a run needs `viewer` on it.
5
+ */
6
+ import { readFile } from 'node:fs/promises';
7
+ import { getJson, postJson } from '../atlas-client.js';
8
+ import { printCliError } from '../cli-errors.js';
9
+ import { PROCESS_RUNS_USAGE } from '../command-help.js';
10
+ import { validateCommandInput } from '../command-input.js';
11
+ import { buildContext, clientOptions } from '../functions/commands.js';
12
+ import { table } from '../text-table.js';
13
+ const RUN_STATUSES = ['pending', 'running', 'completed', 'failed', 'cancelled', 'timed_out'];
14
+ const TERMINAL_STATUSES = new Set(['completed', 'failed', 'cancelled', 'timed_out']);
15
+ const RUN_ID = /^[A-Za-z0-9._-]{2,128}$/;
16
+ const MAX_LIST_LIMIT = 500;
17
+ const DEFAULT_WAIT_SECONDS = 600;
18
+ const WAIT_POLL_MS = 2_000;
19
+ function stringFlag({ args, key }) {
20
+ const value = args.flags[key];
21
+ return typeof value === 'string' ? value : undefined;
22
+ }
23
+ function runIdArg({ args, label }) {
24
+ const value = args.positional[1];
25
+ if (!RUN_ID.test(value))
26
+ throw new Error(`Invalid ${label} '${value}': 2-128 letters, digits, '.', '_' or '-'.`);
27
+ return value;
28
+ }
29
+ function errorText(error) {
30
+ if (error === null || error === undefined)
31
+ return undefined;
32
+ if (typeof error === 'string')
33
+ return error;
34
+ if (typeof error === 'object' && typeof Reflect.get(error, 'message') === 'string')
35
+ return String(Reflect.get(error, 'message'));
36
+ return JSON.stringify(error);
37
+ }
38
+ async function metadataFromFile(path) {
39
+ let parsed;
40
+ try {
41
+ parsed = JSON.parse(await readFile(path, 'utf8'));
42
+ }
43
+ catch (error) {
44
+ throw new Error(`--metadata-file ${path}: ${error instanceof Error ? error.message : String(error)}`);
45
+ }
46
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
47
+ throw new Error(`--metadata-file ${path} must contain a JSON object.`);
48
+ }
49
+ return parsed;
50
+ }
51
+ /** Validate every flag before authenticating so a typo never starts a run. */
52
+ export async function startRunBody(args) {
53
+ validateCommandInput({
54
+ args,
55
+ flags: { version: 'string', 'run-id': 'string', 'metadata-file': 'string', title: 'string', entity: 'string' },
56
+ positional: 2,
57
+ });
58
+ const runId = stringFlag({ args, key: 'run-id' });
59
+ if (runId !== undefined && !RUN_ID.test(runId)) {
60
+ throw new Error(`Invalid --run-id '${runId}': 2-128 letters, digits, '.', '_' or '-'.`);
61
+ }
62
+ const entity = stringFlag({ args, key: 'entity' });
63
+ const separator = entity?.indexOf(':') ?? -1;
64
+ if (entity !== undefined && (separator < 1 || separator === entity.length - 1)) {
65
+ throw new Error(`Invalid --entity '${entity}': expected <type>:<id>.`);
66
+ }
67
+ const metadataFile = stringFlag({ args, key: 'metadata-file' });
68
+ const version = stringFlag({ args, key: 'version' });
69
+ const title = stringFlag({ args, key: 'title' });
70
+ return {
71
+ process_id: args.positional[1],
72
+ ...(version !== undefined ? { version } : {}),
73
+ ...(runId !== undefined ? { run_id: runId } : {}),
74
+ ...(title !== undefined ? { title } : {}),
75
+ ...(entity !== undefined ? { entity: { type: entity.slice(0, separator), id: entity.slice(separator + 1) } } : {}),
76
+ ...(metadataFile !== undefined ? { metadata: await metadataFromFile(metadataFile) } : {}),
77
+ };
78
+ }
79
+ export function listRunsQuery(args) {
80
+ validateCommandInput({
81
+ args,
82
+ flags: { process: 'string', status: 'string', 'entity-type': 'string', 'entity-id': 'string', archived: 'boolean', limit: 'string' },
83
+ positional: 1,
84
+ });
85
+ const params = new URLSearchParams();
86
+ const processId = stringFlag({ args, key: 'process' });
87
+ if (processId !== undefined)
88
+ params.set('process_id', processId);
89
+ const status = stringFlag({ args, key: 'status' });
90
+ if (status !== undefined) {
91
+ if (!RUN_STATUSES.includes(status)) {
92
+ throw new Error(`--status must be one of: ${RUN_STATUSES.join(', ')}.`);
93
+ }
94
+ params.set('status', status);
95
+ }
96
+ const entityType = stringFlag({ args, key: 'entity-type' });
97
+ const entityId = stringFlag({ args, key: 'entity-id' });
98
+ if (entityType !== undefined)
99
+ params.set('entity_type', entityType);
100
+ if (entityId !== undefined)
101
+ params.set('entity_id', entityId);
102
+ if (args.flags.archived === true)
103
+ params.set('archived', 'true');
104
+ const limit = stringFlag({ args, key: 'limit' });
105
+ if (limit !== undefined) {
106
+ const value = /^\d+$/.test(limit) ? Number(limit) : Number.NaN;
107
+ if (!Number.isSafeInteger(value) || value < 1 || value > MAX_LIST_LIMIT) {
108
+ throw new Error(`--limit must be an integer from 1 to ${MAX_LIST_LIMIT}.`);
109
+ }
110
+ params.set('limit', String(value));
111
+ }
112
+ return params;
113
+ }
114
+ function printRunsTable(runs) {
115
+ table({
116
+ headers: ['RUN', 'PROCESS', 'VERSION', 'STATUS', 'STARTED', 'COMPLETED', 'TITLE'],
117
+ rows: runs.map((run) => [run.id, run.processId, run.processVersion, run.status, run.startedAt, run.completedAt, run.title]),
118
+ });
119
+ }
120
+ function printRunDetail({ run, steps }) {
121
+ console.log(`Run: ${run.id} | Process: ${run.processId}@${run.processVersion ?? '—'} | Status: ${run.status}`);
122
+ console.log(`Started: ${run.startedAt ?? '—'} | Completed: ${run.completedAt ?? '—'}`);
123
+ const runError = errorText(run.error);
124
+ if (runError)
125
+ console.log(`Error: ${runError}`);
126
+ table({
127
+ headers: ['NODE', 'KIND', 'ATTEMPT', 'STATUS', 'STARTED', 'COMPLETED', 'ERROR'],
128
+ rows: steps.map((step) => [step.nodeId, step.kind, step.attempt, step.status, step.startedAt, step.completedAt, errorText(step.error)]),
129
+ });
130
+ }
131
+ async function waitForTerminal({ load, timeoutSeconds, sleep, }) {
132
+ const deadline = Date.now() + timeoutSeconds * 1000;
133
+ let detail = await load();
134
+ while (!TERMINAL_STATUSES.has(detail.run.status)) {
135
+ if (Date.now() >= deadline) {
136
+ throw new Error(`Run ${detail.run.id} is still ${detail.run.status} after ${timeoutSeconds}s; it keeps running. Check again with process runs show.`);
137
+ }
138
+ await sleep(WAIT_POLL_MS);
139
+ detail = await load();
140
+ }
141
+ return detail;
142
+ }
143
+ async function startRun({ args, json }) {
144
+ const body = await startRunBody(args);
145
+ const ctx = await buildContext(args);
146
+ const result = await postJson({ ...clientOptions(ctx), path: '/api/lattice/runs', body });
147
+ if (json) {
148
+ console.log(JSON.stringify(result, null, 2));
149
+ return 0;
150
+ }
151
+ const replay = result.idempotent_replay ? ' (existing run; --run-id already used)' : '';
152
+ console.log(`Run: ${result.run_id} | Process: ${result.process_id}@${result.process_version ?? '—'} | Status: ${result.status}${replay}`);
153
+ console.log(`Follow it with: seq-studio process runs show ${result.run_id} --wait`);
154
+ return 0;
155
+ }
156
+ async function listRuns({ args, json }) {
157
+ const params = listRunsQuery(args);
158
+ const ctx = await buildContext(args);
159
+ const query = params.toString();
160
+ const result = await getJson({ ...clientOptions(ctx), path: `/api/lattice/runs${query ? `?${query}` : ''}` });
161
+ if (json)
162
+ console.log(JSON.stringify(result, null, 2));
163
+ else {
164
+ printRunsTable(result.runs);
165
+ console.error(`${result.runs.length} run(s), newest first`);
166
+ }
167
+ const limit = Number(params.get('limit') ?? 50);
168
+ if (result.runs.length >= limit) {
169
+ console.error(`Showing the newest ${limit}. Narrow with --process/--status/--entity-type, or raise --limit (max ${MAX_LIST_LIMIT}).`);
170
+ }
171
+ return 0;
172
+ }
173
+ function waitTimeoutSeconds(args) {
174
+ const timeout = stringFlag({ args, key: 'timeout' });
175
+ if (timeout !== undefined && args.flags.wait !== true)
176
+ throw new Error('--timeout applies only with --wait.');
177
+ const seconds = timeout === undefined ? DEFAULT_WAIT_SECONDS : Number(timeout);
178
+ if (!Number.isSafeInteger(seconds) || seconds < 1)
179
+ throw new Error('--timeout must be a positive number of seconds.');
180
+ return seconds;
181
+ }
182
+ async function showRun({ args, json, sleep }) {
183
+ validateCommandInput({ args, flags: { wait: 'boolean', timeout: 'string' }, positional: 2 });
184
+ const runId = runIdArg({ args, label: 'run id' });
185
+ const timeoutSeconds = waitTimeoutSeconds(args);
186
+ const ctx = await buildContext(args);
187
+ const load = () => getJson({ ...clientOptions(ctx), path: `/api/lattice/runs/${encodeURIComponent(runId)}` });
188
+ const detail = args.flags.wait === true ? await waitForTerminal({ load, timeoutSeconds, sleep }) : await load();
189
+ if (json)
190
+ console.log(JSON.stringify(detail, null, 2));
191
+ else
192
+ printRunDetail(detail);
193
+ return 0;
194
+ }
195
+ async function cancelRun({ args, json }) {
196
+ validateCommandInput({ args, flags: {}, positional: 2 });
197
+ const runId = runIdArg({ args, label: 'run id' });
198
+ const ctx = await buildContext(args);
199
+ const result = await postJson({
200
+ ...clientOptions(ctx),
201
+ path: `/api/lattice/runs/${encodeURIComponent(runId)}/cancel`,
202
+ });
203
+ if (json)
204
+ console.log(JSON.stringify(result, null, 2));
205
+ else
206
+ console.log(`Run: ${runId} | Status: ${result.run?.status ?? 'unknown'}${result.idempotent_replay ? ' (already cancelled)' : ''}`);
207
+ return 0;
208
+ }
209
+ const RUN_ACTIONS = {
210
+ start: startRun,
211
+ list: listRuns,
212
+ show: showRun,
213
+ cancel: cancelRun,
214
+ };
215
+ export async function processRunsCommand(args, deps = {}) {
216
+ const action = args.positional[0];
217
+ if (!action || args.flags.help === true || action === 'help') {
218
+ console.log(PROCESS_RUNS_USAGE);
219
+ return action ? 0 : 1;
220
+ }
221
+ const handler = RUN_ACTIONS[action];
222
+ if (!handler) {
223
+ console.error(`unknown process runs command: ${action}`);
224
+ console.error(PROCESS_RUNS_USAGE);
225
+ return 1;
226
+ }
227
+ try {
228
+ return await handler({
229
+ args,
230
+ json: args.flags.json === true,
231
+ sleep: deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
232
+ });
233
+ }
234
+ catch (error) {
235
+ printCliError(error);
236
+ return 1;
237
+ }
238
+ }
@@ -12,7 +12,16 @@ const statusSchema = z.object({
12
12
  }).nullable(),
13
13
  currentRunId: z.string().nullable(),
14
14
  runs: z.array(z.object({ id: z.string(), state: z.string(), error: z.string().nullable().optional() })),
15
+ intents: z.array(z.object({
16
+ id: z.string(), runId: z.string(), state: z.string(), mergeSha: z.string().nullable(),
17
+ error: z.string().nullable(), appUrl: z.string().nullable(),
18
+ targets: z.record(z.string(), z.object({ state: z.string(), reason: z.string().optional() }).passthrough()),
19
+ })).optional(),
15
20
  });
21
+ function oneLine(value) {
22
+ const normalized = value.replace(/\s+/g, ' ').trim();
23
+ return normalized.length > 240 ? `${normalized.slice(0, 237)}...` : normalized;
24
+ }
16
25
  function printPlan({ plan }) {
17
26
  console.log(` Head: ${plan.headSha}; plan: ${plan.planHash}`);
18
27
  for (const target of plan.targets) {
@@ -23,6 +32,24 @@ function printPlan({ plan }) {
23
32
  for (const finding of plan.findings)
24
33
  console.log(` ${finding.severity} ${finding.code}: ${finding.message}`);
25
34
  }
35
+ function printIntents({ intents }) {
36
+ if (intents.length === 0)
37
+ return;
38
+ console.log(` Deployment intents:${intents.length > 5 ? ` (showing 5 of ${intents.length}; use --json for all)` : ''}`);
39
+ for (const intent of intents.slice(0, 5)) {
40
+ console.log(` ${oneLine(intent.id)}: ${oneLine(intent.state)} (${intent.mergeSha ? `merge ${oneLine(intent.mergeSha)}` : 'merge pending'}, run ${oneLine(intent.runId)})`);
41
+ if (intent.error)
42
+ console.log(` Error: ${oneLine(intent.error)}`);
43
+ if (intent.appUrl)
44
+ console.log(` App: ${oneLine(intent.appUrl)}`);
45
+ const targets = Object.entries(intent.targets);
46
+ for (const [key, progress] of targets.slice(0, 10)) {
47
+ console.log(` ${oneLine(key)}: ${oneLine(progress.state)}${progress.reason ? ` — ${oneLine(progress.reason)}` : ''}`);
48
+ }
49
+ if (targets.length > 10)
50
+ console.log(` ... ${targets.length - 10} more targets (use --json)`);
51
+ }
52
+ }
26
53
  /** Read the authoritative server plan; the CLI never infers execution or deployment authority. */
27
54
  export async function showRepositoryPrCi({ ctx, repoId, repoPath, number, json }) {
28
55
  const response = await getJson({ ...clientOptions(ctx), path: `/api/git-service/repos/${repoId}/pulls/${number}/ci` });
@@ -45,5 +72,6 @@ export async function showRepositoryPrCi({ ctx, repoId, repoPath, number, json }
45
72
  }
46
73
  for (const run of status.runs.slice(0, 5))
47
74
  console.log(` ${run.id === status.currentRunId ? 'Current' : 'Previous'} run ${run.id}: ${run.state}${run.error ? ` — ${run.error}` : ''}`);
75
+ printIntents({ intents: status.intents ?? [] });
48
76
  return blocked ? 1 : 0;
49
77
  }
@@ -27,6 +27,7 @@ import { confirmYes } from '../prompt.js';
27
27
  import { buildContext, clientOptions, flagBool, LOG, } from '../functions/commands.js';
28
28
  import { looksLikeCommitSha, runGitClone, } from './git-clone.js';
29
29
  import { configureGitLogin } from './git-credential.js';
30
+ import { isSandboxTokenMode } from '../sandbox-auth.js';
30
31
  const PAGE_SIZE = 200;
31
32
  // ---------------------------------------------------------------------------
32
33
  // Helpers
@@ -415,7 +416,10 @@ export async function reposCloneCommand(args, deps = {}) {
415
416
  console.log(`${LOG} cloned ${positional ?? targetUrl} → ${destDir}` +
416
417
  (ref ? ` (ref ${ref})` : '') +
417
418
  ` via smart-HTTP${depth != null ? ` (depth ${depth})` : ''}`);
418
- console.log(`${LOG} git pull/push now use your seq-studio login. After expiry: seq-studio login --env ${env.name}`);
419
+ console.log(isSandboxTokenMode()
420
+ // The sandbox's token file is rewritten before every tool call; there is no login.
421
+ ? `${LOG} git pull/push now use this agent sandbox's Atlas credential, which renews on every tool call.`
422
+ : `${LOG} git pull/push now use your seq-studio login. After expiry: seq-studio login --env ${env.name}`);
419
423
  return 0;
420
424
  }
421
425
  /**
@@ -707,6 +711,12 @@ export async function reposCiImportCommand(args) {
707
711
  }
708
712
  export async function reposCiCommand(args) {
709
713
  const [requestedAction] = args.positional;
714
+ if (requestedAction && requestedAction !== 'help' &&
715
+ !['init', 'show', 'require', 'import'].includes(requestedAction) &&
716
+ (flagBool(args.flags, 'help') || flagBool(args.flags, 'h'))) {
717
+ console.error(`unknown repos ci command: ${requestedAction}`);
718
+ return 1;
719
+ }
710
720
  const action = flagBool(args.flags, 'help') || flagBool(args.flags, 'h') ? 'help' : requestedAction;
711
721
  const rest = {
712
722
  ...args,
@@ -1,10 +1,11 @@
1
1
  import type { ParsedArgs } from '../process/commands.js';
2
+ export declare const GIT_CREDENTIAL_USAGE: string;
2
3
  /** Only send a login credential to the exact repository pinned at clone time. */
3
4
  export declare function gitCredentialResponse({ input, operation, envName, cloneUrl, }: {
4
5
  input: string;
5
6
  operation: string;
6
- envName: string;
7
- cloneUrl: string;
7
+ envName?: string;
8
+ cloneUrl?: string;
8
9
  }): Promise<string>;
9
10
  /** Store only a helper command, bound to this environment and repository URL. */
10
11
  export declare function configureGitLogin({ destDir, envName, cloneUrl, }: {