@stigmer/cli 3.12.4 → 3.12.5

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 (47) hide show
  1. package/commands/draft.js +4 -2
  2. package/commands/draft.js.map +1 -1
  3. package/commands/run.js +4 -2
  4. package/commands/run.js.map +1 -1
  5. package/commands/seedpack.d.ts.map +1 -1
  6. package/commands/seedpack.js +27 -5
  7. package/commands/seedpack.js.map +1 -1
  8. package/local/seedpack/apply.d.ts +32 -3
  9. package/local/seedpack/apply.d.ts.map +1 -1
  10. package/local/seedpack/apply.js +59 -8
  11. package/local/seedpack/apply.js.map +1 -1
  12. package/package.json +5 -5
  13. package/resources/apply/apply.d.ts.map +1 -1
  14. package/resources/apply/apply.js +10 -1
  15. package/resources/apply/apply.js.map +1 -1
  16. package/resources/connect/connect.d.ts +7 -0
  17. package/resources/connect/connect.d.ts.map +1 -1
  18. package/resources/connect/connect.js +47 -30
  19. package/resources/connect/connect.js.map +1 -1
  20. package/resources/connect/display.d.ts.map +1 -1
  21. package/resources/connect/display.js +3 -0
  22. package/resources/connect/display.js.map +1 -1
  23. package/resources/run/prepare.d.ts +12 -1
  24. package/resources/run/prepare.d.ts.map +1 -1
  25. package/resources/run/prepare.js +27 -2
  26. package/resources/run/prepare.js.map +1 -1
  27. package/resources/task-configs.d.ts +15 -0
  28. package/resources/task-configs.d.ts.map +1 -0
  29. package/resources/task-configs.js +135 -0
  30. package/resources/task-configs.js.map +1 -0
  31. package/resources/validate.d.ts.map +1 -1
  32. package/resources/validate.js +8 -1
  33. package/resources/validate.js.map +1 -1
  34. package/src/commands/draft.ts +4 -2
  35. package/src/commands/run.ts +4 -2
  36. package/src/commands/seedpack.ts +27 -5
  37. package/src/local/seedpack/apply.test.ts +127 -6
  38. package/src/local/seedpack/apply.ts +69 -9
  39. package/src/resources/apply/apply.ts +11 -1
  40. package/src/resources/connect/connect.ts +70 -44
  41. package/src/resources/connect/display.ts +3 -0
  42. package/src/resources/run/prepare.test.ts +80 -0
  43. package/src/resources/run/prepare.ts +41 -1
  44. package/src/resources/task-configs.test.ts +98 -0
  45. package/src/resources/task-configs.ts +150 -0
  46. package/src/resources/validate.test.ts +26 -0
  47. package/src/resources/validate.ts +10 -2
@@ -1,11 +1,19 @@
1
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
1
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import type { Message } from "@bufbuild/protobuf";
5
+ import type { Stigmer } from "@stigmer/sdk";
5
6
  import { afterEach, beforeEach, describe, expect, it } from "vitest";
6
7
  import { buildDeclarativeItems, scanResourceFiles } from "../../resources/apply/declarative.js";
7
8
  import type { ControllerFn } from "../../resources/apply/handlers.js";
8
- import { applySeedpack, resolveSeedpackOrg, seedpackContentHash } from "./apply.js";
9
+ import {
10
+ applySeedpack,
11
+ readServerSeedpackHash,
12
+ resolveSeedpackOrg,
13
+ SEEDPACK_HASH_LABEL,
14
+ SEEDPACK_PROJECT_SLUG,
15
+ seedpackContentHash,
16
+ } from "./apply.js";
9
17
  import type { SeedpackContent } from "./content.js";
10
18
  import { extractSeedpack, readMarker, resolveSeedpackContent } from "./content.js";
11
19
 
@@ -43,27 +51,43 @@ function makeContent(): SeedpackContent {
43
51
  return { dir, source: "repo" };
44
52
  }
45
53
 
46
- // Records each applied message's proto type name; every controller resolves to
47
- // the same stub apply (the handlers only call `.apply`).
48
- function recordingDeps() {
54
+ // Records each applied message (and its proto type name); every controller
55
+ // resolves to the same stub apply (the handlers only call `.apply`).
56
+ function recordingDeps(stigmer?: unknown) {
49
57
  const applied: string[] = [];
58
+ const appliedMessages: Message[] = [];
50
59
  const controller = (() => ({
51
60
  apply: async (m: Message) => {
52
61
  applied.push((m as { $typeName: string }).$typeName);
62
+ appliedMessages.push(m);
53
63
  return m;
54
64
  },
55
65
  })) as unknown as ControllerFn;
56
66
  return {
57
67
  applied,
68
+ appliedMessages,
58
69
  deps: {
59
70
  controller,
60
- stigmer: {} as never,
71
+ stigmer: (stigmer ?? {}) as never,
61
72
  info: () => {},
62
73
  warn: () => {},
63
74
  },
64
75
  };
65
76
  }
66
77
 
78
+ // A Stigmer stub whose project.getByReference reports the given stored hash
79
+ // (null → the label is absent; "absent" → the project itself does not exist).
80
+ function stigmerWithServerHash(stored: string | null | "absent"): Stigmer {
81
+ return {
82
+ project: {
83
+ getByReference: async () => {
84
+ if (stored === "absent") throw new Error("not found");
85
+ return { metadata: { labels: stored === null ? {} : { [SEEDPACK_HASH_LABEL]: stored } } };
86
+ },
87
+ },
88
+ } as unknown as Stigmer;
89
+ }
90
+
67
91
  let content: SeedpackContent;
68
92
  let markerDir: string;
69
93
  beforeEach(() => {
@@ -125,6 +149,91 @@ describe("applySeedpack", () => {
125
149
  expect(result.applied).toBe(true);
126
150
  expect(forced.applied.length).toBeGreaterThan(0);
127
151
  });
152
+
153
+ it("stamps the content hash as a reserved label on the applied Project", async () => {
154
+ const { appliedMessages, deps } = recordingDeps();
155
+ const result = await applySeedpack(deps, { markerDir, content });
156
+
157
+ const project = appliedMessages.find((m) => (m as { $typeName: string }).$typeName.endsWith("Project")) as
158
+ | { metadata?: { labels: Record<string, string> } }
159
+ | undefined;
160
+ expect(project).toBeDefined();
161
+ expect(project?.metadata?.labels[SEEDPACK_HASH_LABEL]).toBe(result.hash);
162
+ });
163
+ });
164
+
165
+ describe("applySeedpack — cloud mode (useServerHash)", () => {
166
+ it("skips when the server's recorded hash matches, without touching the marker", async () => {
167
+ const hash = seedpackContentHash({ content });
168
+ const { applied, deps } = recordingDeps(stigmerWithServerHash(hash));
169
+
170
+ const result = await applySeedpack(deps, { markerDir, content, useServerHash: true });
171
+
172
+ expect(result.applied).toBe(false);
173
+ expect(applied).toHaveLength(0);
174
+ expect(readMarker(markerDir)).toBeNull();
175
+ });
176
+
177
+ it("applies when the server records a different hash — and never writes the marker", async () => {
178
+ const { applied, deps } = recordingDeps(stigmerWithServerHash("sha256:0000000000000000"));
179
+
180
+ const result = await applySeedpack(deps, { markerDir, content, useServerHash: true });
181
+
182
+ expect(result.applied).toBe(true);
183
+ expect(applied.length).toBeGreaterThan(0);
184
+ // Cloud mode's record is the Project label; a marker here would be a
185
+ // second record of the same fact, free to drift.
186
+ expect(readMarker(markerDir)).toBeNull();
187
+ });
188
+
189
+ it("applies when the seedpack Project does not exist yet (first bootstrap)", async () => {
190
+ const { applied, deps } = recordingDeps(stigmerWithServerHash("absent"));
191
+
192
+ const result = await applySeedpack(deps, { markerDir, content, useServerHash: true });
193
+
194
+ expect(result.applied).toBe(true);
195
+ expect(applied.length).toBeGreaterThan(0);
196
+ });
197
+
198
+ it("ignores a stale local marker: the server is the only truth consulted", async () => {
199
+ const hash = seedpackContentHash({ content });
200
+ // A leftover marker from the pre-cloud#429 era says "up to date"…
201
+ const { deps: first } = recordingDeps();
202
+ await applySeedpack(first, { markerDir, content });
203
+ // …but the server has never seen this content.
204
+ const { applied, deps } = recordingDeps(stigmerWithServerHash(null));
205
+
206
+ const result = await applySeedpack(deps, { markerDir, content, useServerHash: true });
207
+
208
+ expect(result.applied).toBe(true);
209
+ expect(applied.length).toBeGreaterThan(0);
210
+ expect(hash).toBe(result.hash);
211
+ });
212
+
213
+ it("re-applies when forced even if the server hash matches", async () => {
214
+ const hash = seedpackContentHash({ content });
215
+ const { applied, deps } = recordingDeps(stigmerWithServerHash(hash));
216
+
217
+ const result = await applySeedpack(deps, { markerDir, content, useServerHash: true, force: true });
218
+
219
+ expect(result.applied).toBe(true);
220
+ expect(applied.length).toBeGreaterThan(0);
221
+ });
222
+ });
223
+
224
+ describe("readServerSeedpackHash", () => {
225
+ it("returns the recorded label", async () => {
226
+ const hash = await readServerSeedpackHash(stigmerWithServerHash("sha256:abcdef0123456789"), "stigmer");
227
+ expect(hash).toBe("sha256:abcdef0123456789");
228
+ });
229
+
230
+ it("returns null when the label is absent", async () => {
231
+ expect(await readServerSeedpackHash(stigmerWithServerHash(null), "stigmer")).toBeNull();
232
+ });
233
+
234
+ it("returns null when the project cannot be read (never applied / transient failure)", async () => {
235
+ expect(await readServerSeedpackHash(stigmerWithServerHash("absent"), "stigmer")).toBeNull();
236
+ });
128
237
  });
129
238
 
130
239
  describe("seedpackContentHash", () => {
@@ -139,6 +248,18 @@ describe("seedpackContentHash", () => {
139
248
  // CI canary manifest) must live outside the content set, never beside the
140
249
  // McpServer YAMLs where `loadDocuments(strict)` would reject it for missing a
141
250
  // `kind`. The synthetic fixtures above can't catch this — only real content can.
251
+ // The cloud-mode hash read addresses the seedpack Project by a pinned slug.
252
+ // The server derives the slug from the manifest's metadata.name, so this pin
253
+ // holds exactly as long as the real seedpack keeps that name — verify against
254
+ // the real content so a rename there fails here, not silently in prod.
255
+ describe("SEEDPACK_PROJECT_SLUG pins the real manifest name", () => {
256
+ it("matches seedpack/stigmer.yaml metadata.name", () => {
257
+ const real = resolveSeedpackContent();
258
+ const manifest = readFileSync(join(real.dir, "stigmer.yaml"), "utf8");
259
+ expect(manifest).toMatch(new RegExp(`name:\\s*${SEEDPACK_PROJECT_SLUG}\\s*$`, "m"));
260
+ });
261
+ });
262
+
142
263
  describe("real seedpack content loads through the declarative scanner", () => {
143
264
  it("scans + builds apply items without a missing-kind error", () => {
144
265
  const real = resolveSeedpackContent();
@@ -10,11 +10,18 @@
10
10
  // 2. the project (stigmer.yaml + agents/skills/mcp-servers/workflows) via the
11
11
  // declarative reconciler, under the target org.
12
12
  //
13
- // Idempotent: a content-hash marker skips the apply when nothing changed.
13
+ // Idempotent, with the applied-hash truth living with the backend it describes
14
+ // (cloud#429): every apply stamps the content hash as a reserved label on the
15
+ // seedpack Project, and cloud-mode runs skip by reading that label back — so
16
+ // any machine (operator laptop, CI) sees the same applied state. Local mode
17
+ // keeps the original marker file (the local data dir lives and dies with the
18
+ // local backend, so a local file IS backend-scoped state there).
14
19
 
15
20
  import { mkdtempSync, rmSync } from "node:fs";
16
21
  import { tmpdir } from "node:os";
17
22
  import { join } from "node:path";
23
+ import { create } from "@bufbuild/protobuf";
24
+ import { ApiResourceMetadataSchema } from "@stigmer/protos/ai/stigmer/commons/apiresource/metadata_pb";
18
25
  import type { Stigmer } from "@stigmer/sdk";
19
26
  import { applyItem, resolveApplyItems } from "../../resources/apply/apply.js";
20
27
  import { applyDeclarative, detectTrack } from "../../resources/apply/declarative.js";
@@ -31,6 +38,23 @@ import {
31
38
  const DEFAULT_ORG = "stigmer";
32
39
  const ORG_ENV_VAR = "STIGMER_SEEDPACK_ORG";
33
40
 
41
+ /**
42
+ * Reserved label on the seedpack Project recording the last applied content
43
+ * hash (cloud#429). Writing a NEW value requires `can_write_reserved_labels`
44
+ * (the seeding identity's capability); re-sending an unchanged value is an
45
+ * echo the cloud guard passes for any caller — so re-applies of identical
46
+ * content are never treated as reserved-label writes.
47
+ */
48
+ export const SEEDPACK_HASH_LABEL = "stigmer.ai/seedpack-hash";
49
+
50
+ /**
51
+ * The seedpack Project's slug. The server derives it from the manifest's
52
+ * `metadata.name` in `seedpack/stigmer.yaml` — "stigmer-seedpack" is already
53
+ * slug-shaped, so name and slug coincide. Pinned by a test against the real
54
+ * content so a rename there fails loudly here.
55
+ */
56
+ export const SEEDPACK_PROJECT_SLUG = "stigmer-seedpack";
57
+
34
58
  export interface SeedpackApplyDeps {
35
59
  /** Raw command-controller accessor (full-proto apply, preserves metadata.id). */
36
60
  readonly controller: ControllerFn;
@@ -43,7 +67,7 @@ export interface SeedpackApplyDeps {
43
67
  }
44
68
 
45
69
  export interface SeedpackApplyOptions {
46
- /** Directory holding the idempotency marker (data dir for local, config dir for cloud). */
70
+ /** Directory holding the idempotency marker (local mode only). */
47
71
  readonly markerDir: string;
48
72
  /** Target org slug. Defaults to STIGMER_SEEDPACK_ORG, then "stigmer". */
49
73
  readonly org?: string;
@@ -52,6 +76,13 @@ export interface SeedpackApplyOptions {
52
76
  /** Pre-resolved content (injectable for tests); resolved on demand otherwise. */
53
77
  readonly content?: SeedpackContent;
54
78
  readonly home?: string;
79
+ /**
80
+ * Cloud mode: the idempotency truth is the {@link SEEDPACK_HASH_LABEL} on the
81
+ * server's seedpack Project, read via {@link readServerSeedpackHash} — the
82
+ * local marker is neither read nor written, so a stateless machine (CI, a
83
+ * second operator laptop) still skips unchanged content correctly.
84
+ */
85
+ readonly useServerHash?: boolean;
55
86
  }
56
87
 
57
88
  export interface SeedpackApplyResult {
@@ -77,17 +108,35 @@ export function seedpackContentHash(opts: Pick<SeedpackApplyOptions, "content" |
77
108
  return hashSeedpackContent(content.dir);
78
109
  }
79
110
 
111
+ /**
112
+ * Read the applied content hash recorded on the backend's seedpack Project,
113
+ * or null when it cannot be proven (project absent — never applied — or the
114
+ * read failed). Null means "apply": the apply itself is idempotent server-side,
115
+ * so an unprovable state costs one redundant pass, never a skipped update.
116
+ */
117
+ export async function readServerSeedpackHash(stigmer: Stigmer, org: string): Promise<string | null> {
118
+ try {
119
+ const project = await stigmer.project.getByReference({ org, slug: SEEDPACK_PROJECT_SLUG });
120
+ return project.metadata?.labels?.[SEEDPACK_HASH_LABEL] ?? null;
121
+ } catch {
122
+ return null;
123
+ }
124
+ }
125
+
80
126
  /**
81
127
  * Apply the seedpack to the backend the deps connect to. Returns `applied:false`
82
- * (without touching the backend) when the marker already matches the content
83
- * hash and `force` is not set.
128
+ * (without touching the backend beyond the cloud-mode hash read) when the
129
+ * recorded hash already matches the content hash and `force` is not set.
84
130
  */
85
131
  export async function applySeedpack(deps: SeedpackApplyDeps, opts: SeedpackApplyOptions): Promise<SeedpackApplyResult> {
86
132
  const org = resolveSeedpackOrg(opts.org);
87
133
  const content = opts.content ?? resolveSeedpackContent({ home: opts.home });
88
134
  const hash = hashSeedpackContent(content.dir);
89
135
 
90
- if (opts.force !== true && readMarker(opts.markerDir) === hash) {
136
+ const appliedHash = opts.useServerHash === true
137
+ ? await readServerSeedpackHash(deps.stigmer, org)
138
+ : readMarker(opts.markerDir);
139
+ if (opts.force !== true && appliedHash === hash) {
91
140
  return { applied: false, hash, org };
92
141
  }
93
142
 
@@ -96,8 +145,12 @@ export async function applySeedpack(deps: SeedpackApplyDeps, opts: SeedpackApply
96
145
  try {
97
146
  extractSeedpack(content.dir, stage);
98
147
  await applyOrganizations(deps, stage);
99
- await applyProject(deps, stage, org);
100
- writeMarker(opts.markerDir, hash);
148
+ await applyProject(deps, stage, org, hash);
149
+ // The Project label written above is the cloud-mode record; the marker
150
+ // stays the local-mode one. Never both — two records of one fact drift.
151
+ if (opts.useServerHash !== true) {
152
+ writeMarker(opts.markerDir, hash);
153
+ }
101
154
  } finally {
102
155
  rmSync(stage, { recursive: true, force: true });
103
156
  }
@@ -124,11 +177,18 @@ async function applyOrganizations(deps: SeedpackApplyDeps, stageDir: string): Pr
124
177
 
125
178
  // Phase 2: the project (agents, skills, MCP servers, workflows) via the shared
126
179
  // declarative reconciler — the same path `stigmer apply` runs for a user project.
127
- async function applyProject(deps: SeedpackApplyDeps, stageDir: string, org: string): Promise<void> {
180
+ //
181
+ // The content hash is stamped as a reserved label on the Project HERE, in the
182
+ // seedpack path only — general `stigmer apply` never writes reserved labels.
183
+ // The stamp rides the project apply that happens anyway, so recording the hash
184
+ // costs no extra RPC and can never succeed while the apply failed.
185
+ async function applyProject(deps: SeedpackApplyDeps, stageDir: string, org: string, contentHash: string): Promise<void> {
128
186
  const detect = detectTrack(stageDir);
129
- if (detect.track !== "declarative") {
187
+ if (detect.track !== "declarative" || detect.project === undefined) {
130
188
  throw new Error(`seedpack is not a declarative project (detected '${detect.track}')`);
131
189
  }
190
+ detect.project.metadata ??= create(ApiResourceMetadataSchema, {});
191
+ detect.project.metadata.labels[SEEDPACK_HASH_LABEL] = contentHash;
132
192
  await applyDeclarative(detect, {
133
193
  controller: deps.controller,
134
194
  stigmer: deps.stigmer,
@@ -8,6 +8,7 @@
8
8
 
9
9
  import { create, fromJson, type JsonValue, type Message } from "@bufbuild/protobuf";
10
10
  import type { McpServer } from "@stigmer/protos/ai/stigmer/agentic/mcpserver/v1/api_pb";
11
+ import type { Workflow } from "@stigmer/protos/ai/stigmer/agentic/workflow/v1/api_pb";
11
12
  import { ApiResourceKind } from "@stigmer/protos/ai/stigmer/commons/apiresource/apiresourcekind/api_resource_kind_pb";
12
13
  import { ApiResourceVisibility } from "@stigmer/protos/ai/stigmer/commons/apiresource/enum_pb";
13
14
  import { UpdateVisibilityInputSchema } from "@stigmer/protos/ai/stigmer/commons/apiresource/io_pb";
@@ -19,6 +20,7 @@ import { UsageError } from "../../errors/index.js";
19
20
  import { CommandResult } from "../../output/index.js";
20
21
  import { defaultRegistry, Verb } from "../../registry/index.js";
21
22
  import { loadDocuments, resolveYamlFiles } from "../documents.js";
23
+ import { decodeWorkflowTaskConfigs } from "../task-configs.js";
22
24
  import { type ApplyHandler, APPLY_HANDLERS, type ControllerFn } from "./handlers.js";
23
25
 
24
26
  export interface ApplyItem {
@@ -112,7 +114,15 @@ export async function applyItem(
112
114
  */
113
115
  export function marshalItem(item: ApplyItem): Message {
114
116
  try {
115
- return fromJson(item.handler.schema, item.document, { ignoreUnknownFields: false });
117
+ const message = fromJson(item.handler.schema, item.document, { ignoreUnknownFields: false });
118
+ // Workflow task_config blocks live inside an open Struct the top-level
119
+ // decode cannot see into; decode them per kind so a dry-run (and the
120
+ // reconciler's marshal) rejects exactly what a real apply rejects
121
+ // (stigmer/stigmer#778).
122
+ if (item.handler.kind === ApiResourceKind.workflow) {
123
+ decodeWorkflowTaskConfigs(message as Workflow);
124
+ }
125
+ return message;
116
126
  } catch (err) {
117
127
  throw new UsageError(`invalid ${item.handler.displayName} in ${item.filePath}: ${(err as Error).message}`);
118
128
  }
@@ -1,7 +1,9 @@
1
- // `connect mcp-server` orchestration. Mirrors Go's mcpserver.Connect (connect.go):
2
- // resolve the server, then either push to the backend (the Connect RPC runs
3
- // discovery server-side and persists capabilities + tool-approval policies) or,
4
- // for --dry-run, discover locally and return without persisting.
1
+ // `connect mcp-server` orchestration. Resolve the server, then either run the
2
+ // server-side connect (discovery + tool-approval classification, persisted on
3
+ // the resource) or, for --dry-run, discover locally and return without
4
+ // persisting. The server-side path uses the async lane — startConnect + poll
5
+ // (stigmer/stigmer#425) — with a blocking-RPC fallback for backends that
6
+ // predate it.
5
7
  //
6
8
  // OAuth: when a server requires OAuth, has no existing grant, and no --env was
7
9
  // supplied, the interactive browser flow (oauth.ts) shepherds the user through
@@ -11,10 +13,12 @@
11
13
 
12
14
  import { create } from "@bufbuild/protobuf";
13
15
  import type { McpServer } from "@stigmer/protos/ai/stigmer/agentic/mcpserver/v1/api_pb";
16
+ import type { ConnectInput } from "@stigmer/protos/ai/stigmer/agentic/mcpserver/v1/io_pb";
14
17
  import { ConnectInputSchema, GetOAuthGrantStatusInputSchema } from "@stigmer/protos/ai/stigmer/agentic/mcpserver/v1/io_pb";
15
18
  import type { DiscoveredCapabilities } from "@stigmer/protos/ai/stigmer/agentic/mcpserver/v1/status_pb";
16
19
  import { ApiResourceKind } from "@stigmer/protos/ai/stigmer/commons/apiresource/apiresourcekind/api_resource_kind_pb";
17
20
  import type { Stigmer } from "@stigmer/sdk";
21
+ import { connectAndWait, ConnectStillRunningError, CONNECT_SETTLE_BOUND_MS } from "@stigmer/sdk";
18
22
  import type { BackendType } from "../../config/config.js";
19
23
  import { CliExitError, ExitCode, UsageError } from "../../errors/index.js";
20
24
  import { defaultRegistry } from "../../registry/index.js";
@@ -49,6 +53,13 @@ export interface ConnectResult {
49
53
  readonly capabilities: DiscoveredCapabilities | undefined;
50
54
  /** Set when capabilities were persisted (non-dry-run); undefined for dry-run. */
51
55
  readonly updated: McpServer | undefined;
56
+ /**
57
+ * Start-time advisory from the backend's connect pre-flight (e.g. "no
58
+ * runner appears to be polling the task queue"). Only set on the async
59
+ * lane, and only when the operation ultimately settled anyway — surfaced
60
+ * so the user learns their runner came up late.
61
+ */
62
+ readonly warning?: string;
52
63
  }
53
64
 
54
65
  /** Connect to an MCP server and discover its capabilities (push or dry-run). */
@@ -75,50 +86,65 @@ export async function connectMcpServer(client: Stigmer, opts: ConnectOptions): P
75
86
 
76
87
  await ensureOAuthSatisfied(client, server, opts);
77
88
 
78
- const push = client.mcpServer.connect(
79
- create(ConnectInputSchema, {
80
- mcpServerId: server.metadata?.id ?? "",
81
- org: opts.org,
82
- runtimeEnv: buildRuntimeEnv(server, opts.envOverrides),
83
- }),
84
- );
85
- const updated = opts.pushTimeoutMs === undefined
86
- ? await push
87
- : await boundedPush(push, opts.pushTimeoutMs, server);
88
- return { server, capabilities: updated.status?.discoveredCapabilities, updated };
89
+ const input = create(ConnectInputSchema, {
90
+ mcpServerId: server.metadata?.id ?? "",
91
+ org: opts.org,
92
+ runtimeEnv: buildRuntimeEnv(server, opts.envOverrides),
93
+ });
94
+ return serverSideConnect(client, server, input, opts);
89
95
  }
90
96
 
91
- // Soft timeout on the server-side connect (the client/client.ts idiom): races
92
- // the RPC against a timer without cancelling it — the backend's connect
93
- // workflow keeps running and persists its result on its own, so the message
94
- // says exactly that instead of implying the connect failed.
95
- async function boundedPush<T>(push: Promise<T>, timeoutMs: number, server: McpServer): Promise<T> {
97
+ // Run the server-side connect through the SDK's shared async-lane protocol
98
+ // (connectAndWait, stigmer/stigmer#425): startConnect + poll, with the
99
+ // blocking-RPC fallback for backends that predate the lane. The CLI's job is
100
+ // only to translate its --timeout semantics and turn a still-running stop
101
+ // into its own actionable guidance.
102
+ async function serverSideConnect(
103
+ client: Stigmer,
104
+ server: McpServer,
105
+ input: ConnectInput,
106
+ opts: ConnectOptions,
107
+ ): Promise<ConnectResult> {
96
108
  const slug = server.metadata?.slug ?? server.metadata?.id ?? "the server";
97
- let timer: NodeJS.Timeout | undefined;
98
- const timeout = new Promise<never>((_, reject) => {
99
- timer = setTimeout(
100
- () =>
101
- reject(
102
- new CliExitError(
103
- `Stopped waiting for the connect of MCP server '${slug}' after ${timeoutMs / 1000}s (--timeout)`,
104
- ExitCode.Connection,
105
- [
106
- "The server-side connect is still running and will persist its result if it succeeds.",
107
- `Check the outcome with: stigmer get mcp-server ${slug}`,
108
- "Re-run without --timeout to wait for completion.",
109
- ],
110
- ),
111
- ),
112
- timeoutMs,
113
- );
114
- });
115
- // The losing push may settle after the CLI has started exiting; swallow its
116
- // late rejection so it cannot surface as an unhandled-rejection crash.
117
- void push.catch(() => {});
109
+ let warning = "";
118
110
  try {
119
- return await Promise.race([push, timeout]);
120
- } finally {
121
- if (timer !== undefined) clearTimeout(timer);
111
+ const updated = await connectAndWait(client.mcpServer, input, {
112
+ deadlineMs: opts.pushTimeoutMs,
113
+ onStarted: (started) => {
114
+ warning = started.status?.connectStatus?.warning ?? "";
115
+ },
116
+ });
117
+ return {
118
+ server,
119
+ capabilities: updated.status?.discoveredCapabilities,
120
+ updated,
121
+ warning: warning !== "" ? warning : undefined,
122
+ };
123
+ } catch (err) {
124
+ if (!(err instanceof ConnectStillRunningError)) throw err;
125
+ if (opts.pushTimeoutMs !== undefined) {
126
+ // The user's explicit --timeout fired: historical soft-bound semantics.
127
+ throw new CliExitError(
128
+ `Stopped waiting for the connect of MCP server '${slug}' after ${opts.pushTimeoutMs / 1000}s (--timeout)`,
129
+ ExitCode.Connection,
130
+ [
131
+ "The server-side connect is still running and will persist its result if it succeeds.",
132
+ `Check the outcome with: stigmer get mcp-server ${slug}`,
133
+ "Re-run without --timeout to wait for completion.",
134
+ ],
135
+ );
136
+ }
137
+ // The SDK's settle bound fired: past the backend's own ceiling, only a
138
+ // connect_status orphaned by a backend restart can still read CONNECTING.
139
+ throw new CliExitError(
140
+ `The connect of MCP server '${slug}' did not settle within ${CONNECT_SETTLE_BOUND_MS / 60_000} minutes`,
141
+ ExitCode.Connection,
142
+ [
143
+ "This usually means the backend restarted mid-operation.",
144
+ `Check the current state with: stigmer get mcp-server ${slug}`,
145
+ "Re-run the connect to start a fresh operation.",
146
+ ],
147
+ );
122
148
  }
123
149
  }
124
150
 
@@ -26,6 +26,9 @@ export function renderConnectResult(result: ConnectResult, sink: ConnectSink, co
26
26
  sink(result.updated !== undefined
27
27
  ? style.green("✓ Connected — capabilities and tool approvals saved")
28
28
  : style.yellow("⚠ Dry run — results not saved to backend"));
29
+ if (result.warning !== undefined) {
30
+ sink(style.yellow(`⚠ ${result.warning}`));
31
+ }
29
32
  sink("");
30
33
  }
31
34
 
@@ -70,6 +70,27 @@ const BASE_FLAGS: AgentExecFlags = {
70
70
  // with no attachments a bare stub suffices.
71
71
  const STUB_CLIENT = { agentExecution: {} } as unknown as Stigmer;
72
72
 
73
+ /** Stub whose whoAmI resolves an account carrying the given preference. */
74
+ function clientWithPreference(defaultNativeModel: string): Stigmer {
75
+ return {
76
+ agentExecution: {},
77
+ identityAccount: {
78
+ whoAmI: () =>
79
+ Promise.resolve({ spec: { preferences: { defaultNativeModel } } }),
80
+ },
81
+ } as unknown as Stigmer;
82
+ }
83
+
84
+ /** Stub whose whoAmI rejects (auth failure, backend without the RPC, ...). */
85
+ function clientWithFailingWhoAmI(): Stigmer {
86
+ return {
87
+ agentExecution: {},
88
+ identityAccount: {
89
+ whoAmI: () => Promise.reject(new Error("unimplemented")),
90
+ },
91
+ } as unknown as Stigmer;
92
+ }
93
+
73
94
  describe("prepareAgentExec env injection", () => {
74
95
  it("injects STIGMER_ORG_ID when absent", async () => {
75
96
  const prepared = await prepareAgentExec(BASE_FLAGS, STUB_CLIENT, "acme");
@@ -103,3 +124,62 @@ describe("prepareAgentExec env injection", () => {
103
124
  expect(prepared.mode).toBe("plan");
104
125
  });
105
126
  });
127
+
128
+ describe("prepareAgentExec account-preference model fill (oss#293 Phase 1.5)", () => {
129
+ it("fills an omitted --model from the account preference on cloud", async () => {
130
+ const prepared = await prepareAgentExec(
131
+ BASE_FLAGS,
132
+ clientWithPreference("claude-sonnet-4.6"),
133
+ "acme",
134
+ undefined,
135
+ { cloudBackend: true },
136
+ );
137
+ expect(prepared.model).toBe("claude-sonnet-4.6");
138
+ });
139
+
140
+ it("an explicit --model always outranks the preference", async () => {
141
+ const prepared = await prepareAgentExec(
142
+ { ...BASE_FLAGS, model: "gpt-5.3" },
143
+ clientWithPreference("claude-sonnet-4.6"),
144
+ "acme",
145
+ undefined,
146
+ { cloudBackend: true },
147
+ );
148
+ expect(prepared.model).toBe("gpt-5.3");
149
+ });
150
+
151
+ it("never consults identity on a local backend", async () => {
152
+ // The failing stub doubles as a call detector: local mode must not even
153
+ // attempt whoAmI, so a rejecting client cannot affect the result.
154
+ const prepared = await prepareAgentExec(
155
+ BASE_FLAGS,
156
+ clientWithFailingWhoAmI(),
157
+ "acme",
158
+ undefined,
159
+ { cloudBackend: false },
160
+ );
161
+ expect(prepared.model).toBe("");
162
+ });
163
+
164
+ it("falls through silently when whoAmI fails — a missing preference never fails a run", async () => {
165
+ const prepared = await prepareAgentExec(
166
+ BASE_FLAGS,
167
+ clientWithFailingWhoAmI(),
168
+ "acme",
169
+ undefined,
170
+ { cloudBackend: true },
171
+ );
172
+ expect(prepared.model).toBe("");
173
+ });
174
+
175
+ it("stays empty when the account declares no native default", async () => {
176
+ const prepared = await prepareAgentExec(
177
+ BASE_FLAGS,
178
+ clientWithPreference(""),
179
+ "acme",
180
+ undefined,
181
+ { cloudBackend: true },
182
+ );
183
+ expect(prepared.model).toBe("");
184
+ });
185
+ });