@stackbone/sdk 0.1.0-alpha.6 → 0.1.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -2373,7 +2373,7 @@ var require_luxon = __commonJS({
2373
2373
  return new Formatter2(locale, opts);
2374
2374
  }
2375
2375
  static parseFormat(fmt) {
2376
- let current = null, currentFull = "", bracketed = false;
2376
+ let current3 = null, currentFull = "", bracketed = false;
2377
2377
  const splits = [];
2378
2378
  for (let i2 = 0; i2 < fmt.length; i2++) {
2379
2379
  const c2 = fmt.charAt(i2);
@@ -2384,12 +2384,12 @@ var require_luxon = __commonJS({
2384
2384
  val: currentFull === "" ? "'" : currentFull
2385
2385
  });
2386
2386
  }
2387
- current = null;
2387
+ current3 = null;
2388
2388
  currentFull = "";
2389
2389
  bracketed = !bracketed;
2390
2390
  } else if (bracketed) {
2391
2391
  currentFull += c2;
2392
- } else if (c2 === current) {
2392
+ } else if (c2 === current3) {
2393
2393
  currentFull += c2;
2394
2394
  } else {
2395
2395
  if (currentFull.length > 0) {
@@ -2399,7 +2399,7 @@ var require_luxon = __commonJS({
2399
2399
  });
2400
2400
  }
2401
2401
  currentFull = c2;
2402
- current = c2;
2402
+ current3 = c2;
2403
2403
  }
2404
2404
  }
2405
2405
  if (currentFull.length > 0) {
@@ -3129,28 +3129,28 @@ var require_luxon = __commonJS({
3129
3129
  __name(durationToMillis, "durationToMillis");
3130
3130
  function normalizeValues(matrix, vals) {
3131
3131
  const factor = durationToMillis(matrix, vals) < 0 ? -1 : 1;
3132
- orderedUnits$1.reduceRight((previous, current) => {
3133
- if (!isUndefined(vals[current])) {
3132
+ orderedUnits$1.reduceRight((previous, current3) => {
3133
+ if (!isUndefined(vals[current3])) {
3134
3134
  if (previous) {
3135
3135
  const previousVal = vals[previous] * factor;
3136
- const conv = matrix[current][previous];
3136
+ const conv = matrix[current3][previous];
3137
3137
  const rollUp = Math.floor(previousVal / conv);
3138
- vals[current] += rollUp * factor;
3138
+ vals[current3] += rollUp * factor;
3139
3139
  vals[previous] -= rollUp * conv * factor;
3140
3140
  }
3141
- return current;
3141
+ return current3;
3142
3142
  } else {
3143
3143
  return previous;
3144
3144
  }
3145
3145
  }, null);
3146
- orderedUnits$1.reduce((previous, current) => {
3147
- if (!isUndefined(vals[current])) {
3146
+ orderedUnits$1.reduce((previous, current3) => {
3147
+ if (!isUndefined(vals[current3])) {
3148
3148
  if (previous) {
3149
3149
  const fraction = vals[previous] % 1;
3150
3150
  vals[previous] -= fraction;
3151
- vals[current] += fraction * matrix[previous][current];
3151
+ vals[current3] += fraction * matrix[previous][current3];
3152
3152
  }
3153
- return current;
3153
+ return current3;
3154
3154
  } else {
3155
3155
  return previous;
3156
3156
  }
@@ -4263,21 +4263,21 @@ var require_luxon = __commonJS({
4263
4263
  * @return {Array}
4264
4264
  */
4265
4265
  static merge(intervals) {
4266
- const [found, final] = intervals.sort((a2, b2) => a2.s - b2.s).reduce(([sofar, current], item) => {
4267
- if (!current) {
4266
+ const [found, final] = intervals.sort((a2, b2) => a2.s - b2.s).reduce(([sofar, current3], item) => {
4267
+ if (!current3) {
4268
4268
  return [
4269
4269
  sofar,
4270
4270
  item
4271
4271
  ];
4272
- } else if (current.overlaps(item) || current.abutsStart(item)) {
4272
+ } else if (current3.overlaps(item) || current3.abutsStart(item)) {
4273
4273
  return [
4274
4274
  sofar,
4275
- current.union(item)
4275
+ current3.union(item)
4276
4276
  ];
4277
4277
  } else {
4278
4278
  return [
4279
4279
  sofar.concat([
4280
- current
4280
+ current3
4281
4281
  ]),
4282
4282
  item
4283
4283
  ];
@@ -5209,7 +5209,7 @@ var require_luxon = __commonJS({
5209
5209
  }
5210
5210
  __name(possiblyCachedLocalWeekData, "possiblyCachedLocalWeekData");
5211
5211
  function clone(inst, alts) {
5212
- const current = {
5212
+ const current3 = {
5213
5213
  ts: inst.ts,
5214
5214
  zone: inst.zone,
5215
5215
  c: inst.c,
@@ -5218,9 +5218,9 @@ var require_luxon = __commonJS({
5218
5218
  invalid: inst.invalid
5219
5219
  };
5220
5220
  return new DateTime({
5221
- ...current,
5221
+ ...current3,
5222
5222
  ...alts,
5223
- old: current
5223
+ old: current3
5224
5224
  });
5225
5225
  }
5226
5226
  __name(clone, "clone");
@@ -8225,7 +8225,7 @@ var require_expression = __commonJS({
8225
8225
  return schedule;
8226
8226
  }, "prev");
8227
8227
  CronExpression.prototype.hasNext = function() {
8228
- var current = this._currentDate;
8228
+ var current3 = this._currentDate;
8229
8229
  var hasIterated = this._hasIterated;
8230
8230
  try {
8231
8231
  this._findSchedule();
@@ -8233,12 +8233,12 @@ var require_expression = __commonJS({
8233
8233
  } catch (err3) {
8234
8234
  return false;
8235
8235
  } finally {
8236
- this._currentDate = current;
8236
+ this._currentDate = current3;
8237
8237
  this._hasIterated = hasIterated;
8238
8238
  }
8239
8239
  };
8240
8240
  CronExpression.prototype.hasPrev = function() {
8241
- var current = this._currentDate;
8241
+ var current3 = this._currentDate;
8242
8242
  var hasIterated = this._hasIterated;
8243
8243
  try {
8244
8244
  this._findSchedule(true);
@@ -8246,7 +8246,7 @@ var require_expression = __commonJS({
8246
8246
  } catch (err3) {
8247
8247
  return false;
8248
8248
  } finally {
8249
- this._currentDate = current;
8249
+ this._currentDate = current3;
8250
8250
  this._hasIterated = hasIterated;
8251
8251
  }
8252
8252
  };
@@ -8753,9 +8753,11 @@ var CAPABILITIES = [
8753
8753
  "prompts.basic",
8754
8754
  // `connections.actions`: the agent → control-plane connectors proxy
8755
8755
  // (feature connectors-connections-automations). Role-based naming per repo
8756
- // convention. `client.connections.list()` / `.invoke(connector, action, args)`
8756
+ // convention. `client.legacyConnections.list()` / `.invoke(connector, action, args)`
8757
8757
  // run against the proxy; the agent container never sees a credential. The
8758
- // v13 bump reintroduces this capability after v12 removed it.
8758
+ // v13 bump reintroduces this capability after v12 removed it. The capability
8759
+ // string stays `connections.actions` (it names the wire domain, not the
8760
+ // renamed SDK accessor).
8759
8761
  "connections.actions"
8760
8762
  ];
8761
8763
  var MODULE_CAPABILITIES = {
@@ -8772,10 +8774,11 @@ var MODULE_CAPABILITIES = {
8772
8774
  // row is still declared here because the table is shared with the cloud
8773
8775
  // contract / Studio capability advertisement.
8774
8776
  prompts: "prompts.basic",
8775
- // `client.connections` is a control-plane PROXY surface (like queues): the
8776
- // agent POSTs to `/api/v1/agent/connections/*` with its agent JWT and the
8777
+ // `client.legacyConnections` is a control-plane PROXY surface (like queues):
8778
+ // the agent POSTs to `/api/v1/agent/connections/*` with its agent JWT and the
8777
8779
  // control plane runs the connector action with credentials resolved in
8778
- // memory. Gated against `connections.actions`.
8780
+ // memory. Gated against `connections.actions`. The map key stays `connections`
8781
+ // (it is the module id shared with the cloud contract, not the SDK accessor).
8779
8782
  connections: "connections.actions"
8780
8783
  };
8781
8784
  var contractBuildNameSchema = zod.z.enum([
@@ -9194,9 +9197,9 @@ function createContractStore(resolved = resolveConfig({})) {
9194
9197
  function peek(baseUrl) {
9195
9198
  if (!baseUrl || baseUrl.trim() === "") return null;
9196
9199
  const key = normaliseBaseUrl(baseUrl);
9197
- const cached = lastResolved.get(key);
9198
- if (!cached || cached.error) return null;
9199
- return cached.data;
9200
+ const cached2 = lastResolved.get(key);
9201
+ if (!cached2 || cached2.error) return null;
9202
+ return cached2.data;
9200
9203
  }
9201
9204
  __name(peek, "peek");
9202
9205
  function gatingEnabled() {
@@ -9462,9 +9465,9 @@ var HttpClient = class {
9462
9465
  if (jwt && !requestHeaders.has("Authorization")) {
9463
9466
  requestHeaders.set("Authorization", `Bearer ${jwt}`);
9464
9467
  }
9465
- const installationId = resolveInstallationId(this.resolved);
9466
- if (installationId && !requestHeaders.has("X-Stackbone-Installation-Id")) {
9467
- requestHeaders.set("X-Stackbone-Installation-Id", installationId);
9468
+ const installationId2 = resolveInstallationId(this.resolved);
9469
+ if (installationId2 && !requestHeaders.has("X-Stackbone-Installation-Id")) {
9470
+ requestHeaders.set("X-Stackbone-Installation-Id", installationId2);
9468
9471
  }
9469
9472
  const body = serializeBody(method, options.body, requestHeaders);
9470
9473
  let lastError = null;
@@ -9962,7 +9965,7 @@ var ApprovalFacade = class {
9962
9965
  const rows = await this._getDatabase().runShared((db) => db`
9963
9966
  INSERT INTO stackbone_platform.approvals (
9964
9967
  topic, payload, callback_url, idempotency_key,
9965
- fallback, metadata, timeout_at
9968
+ fallback, metadata, run_id, requested_by_step_id, timeout_at
9966
9969
  ) VALUES (
9967
9970
  ${options.topic},
9968
9971
  ${JSON.stringify(options.payload ?? {})}::jsonb,
@@ -9970,6 +9973,8 @@ var ApprovalFacade = class {
9970
9973
  ${options.idempotencyKey ?? null},
9971
9974
  ${fallback},
9972
9975
  ${JSON.stringify(options.metadata ?? {})}::jsonb,
9976
+ ${options.runId ?? null}::uuid,
9977
+ ${options.requestedByStepId ?? null}::uuid,
9973
9978
  now() + (${timeoutMs}::int * interval '1 millisecond')
9974
9979
  )
9975
9980
  ON CONFLICT (workspace_id, topic, idempotency_key)
@@ -10202,7 +10207,7 @@ var ConfigFacade = class {
10202
10207
  void this._resolved;
10203
10208
  }
10204
10209
  async get(key) {
10205
- if (!key.trim()) {
10210
+ if (!String(key).trim()) {
10206
10211
  return err({
10207
10212
  code: "config_invalid_request",
10208
10213
  message: "`key` is required."
@@ -10213,7 +10218,7 @@ var ConfigFacade = class {
10213
10218
  if (!payload.data || !(key in payload.data)) {
10214
10219
  return err({
10215
10220
  code: "config_not_found",
10216
- message: `Config key \`${key}\` is not set for this agent.`,
10221
+ message: `Config key \`${String(key)}\` is not set for this agent.`,
10217
10222
  meta: {
10218
10223
  key
10219
10224
  }
@@ -10242,6 +10247,17 @@ var ConfigFacade = class {
10242
10247
  }
10243
10248
  return ok(out);
10244
10249
  }
10250
+ /**
10251
+ * Returns the agent's entire config payload as one typed object. An
10252
+ * absent/null `agent_config` row resolves to `ok({})` — an empty config is
10253
+ * "no config set", consistent with the facade reading the singleton row.
10254
+ * Reads stay an unvalidated SELECT (no AJV on the read path).
10255
+ */
10256
+ async getAll() {
10257
+ const payload = await this.loadPayload();
10258
+ if (payload.error) return err(payload.error);
10259
+ return ok(payload.data ?? {});
10260
+ }
10245
10261
  async loadPayload() {
10246
10262
  const sql = this.sql();
10247
10263
  if (sql.error) return err(sql.error);
@@ -10427,21 +10443,21 @@ function buildProxy(steps, seed, rootCall, gate) {
10427
10443
  }
10428
10444
  __name(buildProxy, "buildProxy");
10429
10445
  function replayChain(seed, steps) {
10430
- let current = seed;
10446
+ let current3 = seed;
10431
10447
  for (const step of steps) {
10432
- if (current === null || current === void 0) return current;
10448
+ if (current3 === null || current3 === void 0) return current3;
10433
10449
  if (step.kind === "get") {
10434
- current = current[step.key];
10450
+ current3 = current3[step.key];
10435
10451
  continue;
10436
10452
  }
10437
- const parent = current;
10453
+ const parent = current3;
10438
10454
  const fn = parent[step.key];
10439
10455
  if (typeof fn !== "function") {
10440
10456
  throw new TypeError(`[stackbone/sdk] cold-start retry could not replay "${step.key}": not a function on the rebuilt handle`);
10441
10457
  }
10442
- current = fn.apply(parent, step.args);
10458
+ current3 = fn.apply(parent, step.args);
10443
10459
  }
10444
- return current;
10460
+ return current3;
10445
10461
  }
10446
10462
  __name(replayChain, "replayChain");
10447
10463
 
@@ -10801,11 +10817,11 @@ var PromptsFacade = class {
10801
10817
  WHERE p.key = ${key} AND p.deleted_at IS NULL
10802
10818
  LIMIT 1
10803
10819
  `;
10804
- const current = existing[0];
10805
- if (!current) return null;
10806
- let nextVersion = current.current_version;
10820
+ const current3 = existing[0];
10821
+ if (!current3) return null;
10822
+ let nextVersion = current3.current_version;
10807
10823
  if (options.template !== void 0) {
10808
- nextVersion = current.current_version + 1;
10824
+ nextVersion = current3.current_version + 1;
10809
10825
  const variables = extractVars(options.template);
10810
10826
  await tx`
10811
10827
  INSERT INTO stackbone_platform.prompt_versions
@@ -10819,8 +10835,8 @@ var PromptsFacade = class {
10819
10835
  await tx`
10820
10836
  UPDATE stackbone_platform.prompts
10821
10837
  SET current_version = ${nextVersion},
10822
- name = ${options.name ?? current.name},
10823
- description = ${options.description !== void 0 ? options.description : current.description},
10838
+ name = ${options.name ?? current3.name},
10839
+ description = ${options.description !== void 0 ? options.description : current3.description},
10824
10840
  metadata = COALESCE(${options.metadata !== void 0 ? JSON.stringify(options.metadata) : null}::jsonb, metadata),
10825
10841
  updated_at = now()
10826
10842
  WHERE key = ${key}
@@ -11242,7 +11258,7 @@ async function createDocument(sql, args) {
11242
11258
  `;
11243
11259
  const insertedDoc = await tx`
11244
11260
  INSERT INTO stackbone_platform.rag_documents (collection_id, source, content_hash, metadata)
11245
- VALUES (${collectionId}, ${args.source}, ${args.contentHash}, ${tx.json(args.metadata)})
11261
+ VALUES (${collectionId}, ${args.source}, ${args.contentHash}, ${JSON.stringify(args.metadata)}::jsonb)
11246
11262
  RETURNING id
11247
11263
  `;
11248
11264
  const documentId = insertedDoc[0]?.id;
@@ -16001,6 +16017,164 @@ var SecretsFacade = class {
16001
16017
  }
16002
16018
  }
16003
16019
  };
16020
+
16021
+ // src/runtime/workflow-scheduler.ts
16022
+ var current;
16023
+ function setWorkflowScheduler(scheduler) {
16024
+ current = scheduler;
16025
+ }
16026
+ __name(setWorkflowScheduler, "setWorkflowScheduler");
16027
+ function getWorkflowScheduler() {
16028
+ if (!current) {
16029
+ throw new Error("No workflow scheduler is bound. `scheduleWorkflow` / `unschedule` / `listSchedules` can only be called inside a running workflow runtime \u2014 the runtime binds the scheduler on its first dispatch.");
16030
+ }
16031
+ return current;
16032
+ }
16033
+ __name(getWorkflowScheduler, "getWorkflowScheduler");
16034
+
16035
+ // src/surfaces/agent-local/workflows/schedule-workflow.ts
16036
+ async function scheduleWorkflow(name, input, cron) {
16037
+ return getWorkflowScheduler().schedule(name, input, cron);
16038
+ }
16039
+ __name(scheduleWorkflow, "scheduleWorkflow");
16040
+ async function unschedule(name) {
16041
+ return getWorkflowScheduler().unschedule(name);
16042
+ }
16043
+ __name(unschedule, "unschedule");
16044
+ async function listSchedules() {
16045
+ return getWorkflowScheduler().listSchedules();
16046
+ }
16047
+ __name(listSchedules, "listSchedules");
16048
+
16049
+ // src/runtime/workflow-starter.ts
16050
+ var current2;
16051
+ function setWorkflowStarter(starter) {
16052
+ current2 = starter;
16053
+ }
16054
+ __name(setWorkflowStarter, "setWorkflowStarter");
16055
+ function getWorkflowStarter() {
16056
+ if (!current2) {
16057
+ throw new Error("No workflow starter is bound. `startWorkflow` / `startWorkflowAndWait` can only be called from inside a running workflow \u2014 the runtime binds the starter on its first dispatch.");
16058
+ }
16059
+ return current2;
16060
+ }
16061
+ __name(getWorkflowStarter, "getWorkflowStarter");
16062
+
16063
+ // src/surfaces/agent-local/workflows/start-workflow.ts
16064
+ async function startWorkflow(name, input, opts) {
16065
+ "use step";
16066
+ return getWorkflowStarter().start(name, input, opts);
16067
+ }
16068
+ __name(startWorkflow, "startWorkflow");
16069
+
16070
+ // src/surfaces/agent-local/workflows/start-workflow-and-wait.ts
16071
+ async function startWorkflowAndWait(name, input, opts) {
16072
+ "use step";
16073
+ return await getWorkflowStarter().startAndWait(name, input, opts);
16074
+ }
16075
+ __name(startWorkflowAndWait, "startWorkflowAndWait");
16076
+
16077
+ // src/surfaces/agent-local/workflows/workflows-accessor.ts
16078
+ var workflows = {
16079
+ start: startWorkflow,
16080
+ startAndWait: startWorkflowAndWait,
16081
+ schedule: scheduleWorkflow,
16082
+ unschedule,
16083
+ listSchedules
16084
+ };
16085
+ function agentRegistry() {
16086
+ const raw = process.env["AGENT_URLS"];
16087
+ if (!raw) {
16088
+ throw new Error("AGENT_URLS is not set. The emulator injects it; run this workflow through `stackbone dev`.");
16089
+ }
16090
+ return JSON.parse(raw);
16091
+ }
16092
+ __name(agentRegistry, "agentRegistry");
16093
+ function resolveAgentHost(name) {
16094
+ const registry = agentRegistry();
16095
+ const host = registry[name];
16096
+ if (!host) {
16097
+ throw new Error(`Unknown agent "${name}". Known agents: ${Object.keys(registry).join(", ")}`);
16098
+ }
16099
+ return host;
16100
+ }
16101
+ __name(resolveAgentHost, "resolveAgentHost");
16102
+ function signWorkflowHeaders() {
16103
+ const secret = process.env["HMAC_SECRET"] ?? "";
16104
+ const timestamp = String(Date.now());
16105
+ const signature = crypto$1.createHmac("sha256", secret).update(timestamp).digest("hex");
16106
+ return {
16107
+ "x-stackbone-timestamp": timestamp,
16108
+ "x-stackbone-workflow-signature": signature
16109
+ };
16110
+ }
16111
+ __name(signWorkflowHeaders, "signWorkflowHeaders");
16112
+
16113
+ // src/surfaces/external/agents/lazy-agent.ts
16114
+ var EVE_CLIENT_MODULE = "eve/client";
16115
+ async function buildEveClient(name) {
16116
+ const host = resolveAgentHost(name);
16117
+ const { Client } = await import(EVE_CLIENT_MODULE);
16118
+ return new Client({
16119
+ host,
16120
+ headers: /* @__PURE__ */ __name(() => signWorkflowHeaders(), "headers")
16121
+ });
16122
+ }
16123
+ __name(buildEveClient, "buildEveClient");
16124
+ function seedSessionState(seed) {
16125
+ if (typeof seed === "string") return {
16126
+ continuationToken: seed,
16127
+ streamIndex: 0
16128
+ };
16129
+ return seed ?? {
16130
+ streamIndex: 0
16131
+ };
16132
+ }
16133
+ __name(seedSessionState, "seedSessionState");
16134
+ function lazyAgentSession(getClient, seed) {
16135
+ const seededState = seedSessionState(seed);
16136
+ let real;
16137
+ let opened;
16138
+ const session = /* @__PURE__ */ __name(() => {
16139
+ real ??= getClient().then((client) => client.session(seed)).then((s2) => {
16140
+ opened = s2;
16141
+ return s2;
16142
+ }).catch((error) => {
16143
+ real = void 0;
16144
+ throw error;
16145
+ });
16146
+ return real;
16147
+ }, "session");
16148
+ return {
16149
+ get state() {
16150
+ return opened ? opened.state : seededState;
16151
+ },
16152
+ async send(input) {
16153
+ return (await session()).send(input);
16154
+ },
16155
+ async *stream(options) {
16156
+ yield* (await session()).stream(options);
16157
+ }
16158
+ };
16159
+ }
16160
+ __name(lazyAgentSession, "lazyAgentSession");
16161
+ function lazyAgent(name) {
16162
+ let client;
16163
+ const getClient = /* @__PURE__ */ __name(() => {
16164
+ client ??= buildEveClient(name).catch((error) => {
16165
+ client = void 0;
16166
+ throw error;
16167
+ });
16168
+ return client;
16169
+ }, "getClient");
16170
+ return {
16171
+ session(state) {
16172
+ return lazyAgentSession(getClient, state);
16173
+ }
16174
+ };
16175
+ }
16176
+ __name(lazyAgent, "lazyAgent");
16177
+ var agent = /* @__PURE__ */ __name((name) => lazyAgent(name), "agent");
16004
16178
  var AiModule = class {
16005
16179
  static {
16006
16180
  __name(this, "AiModule");
@@ -16331,6 +16505,95 @@ function mapApiError(raw, model) {
16331
16505
  };
16332
16506
  }
16333
16507
  __name(mapApiError, "mapApiError");
16508
+ var TIMESTAMP_HEADER = "x-stackbone-timestamp";
16509
+ var SIGNATURE_HEADER2 = "x-stackbone-workflow-signature";
16510
+ function signBrokerHeaders() {
16511
+ const secret = process.env["HMAC_SECRET"] ?? "";
16512
+ const timestamp = String(Date.now());
16513
+ const signature = crypto$1.createHmac("sha256", secret).update(timestamp).digest("hex");
16514
+ return {
16515
+ [TIMESTAMP_HEADER]: timestamp,
16516
+ [SIGNATURE_HEADER2]: signature
16517
+ };
16518
+ }
16519
+ __name(signBrokerHeaders, "signBrokerHeaders");
16520
+ function brokerBaseUrl() {
16521
+ const url = process.env["STACKBONE_API_URL"];
16522
+ if (!url) {
16523
+ throw new Error("STACKBONE_API_URL is not set. The Stackbone runtime injects the broker base URL; run this agent through `stackbone dev`.");
16524
+ }
16525
+ return url.replace(/\/+$/, "");
16526
+ }
16527
+ __name(brokerBaseUrl, "brokerBaseUrl");
16528
+ function installationId() {
16529
+ const id = process.env["STACKBONE_INSTALLATION_ID"];
16530
+ if (!id) {
16531
+ throw new Error("STACKBONE_INSTALLATION_ID is not set. The Stackbone runtime injects it; run this agent through `stackbone dev`.");
16532
+ }
16533
+ return id;
16534
+ }
16535
+ __name(installationId, "installationId");
16536
+
16537
+ // src/surfaces/external/connect/call-connector.ts
16538
+ var EXECUTE_PATH = "/api/connect/execute";
16539
+ function connectorCallError(code, message) {
16540
+ const error = new Error(message);
16541
+ error.code = code;
16542
+ return error;
16543
+ }
16544
+ __name(connectorCallError, "connectorCallError");
16545
+ function errorFromBody(status, body) {
16546
+ if (body && body.ok === false && body.error && typeof body.error.code === "string") {
16547
+ return connectorCallError(body.error.code, body.error.message ?? `Stackbone Connect broker rejected the call (code "${body.error.code}").`);
16548
+ }
16549
+ return connectorCallError("credential_error", `Stackbone Connect broker responded ${status}.`);
16550
+ }
16551
+ __name(errorFromBody, "errorFromBody");
16552
+ async function callConnector(connector, operation, args, opts) {
16553
+ const principal = opts?.principal ?? {
16554
+ type: "app"
16555
+ };
16556
+ const url = `${brokerBaseUrl()}${EXECUTE_PATH}`;
16557
+ const body = JSON.stringify({
16558
+ connector,
16559
+ operation,
16560
+ args: args ?? {},
16561
+ principal,
16562
+ installationId: installationId()
16563
+ });
16564
+ let response;
16565
+ try {
16566
+ response = await fetch(url, {
16567
+ method: "POST",
16568
+ headers: {
16569
+ "content-type": "application/json",
16570
+ ...signBrokerHeaders()
16571
+ },
16572
+ body
16573
+ });
16574
+ } catch (cause) {
16575
+ throw connectorCallError("execute_failed", `Stackbone Connect broker is unreachable: ${cause instanceof Error ? cause.message : String(cause)}`);
16576
+ }
16577
+ const parsed = await response.json().catch(() => null);
16578
+ if (!response.ok || parsed && parsed.ok === false) {
16579
+ throw errorFromBody(response.status, parsed ?? null);
16580
+ }
16581
+ if (!parsed || parsed.ok !== true) {
16582
+ throw connectorCallError("invalid_output", "Stackbone Connect broker returned a malformed execute response.");
16583
+ }
16584
+ return parsed.output;
16585
+ }
16586
+ __name(callConnector, "callConnector");
16587
+ var connectorHandle = /* @__PURE__ */ __name((id) => new Proxy(/* @__PURE__ */ Object.create(null), {
16588
+ get(_target, prop) {
16589
+ if (typeof prop !== "string" || prop === "then") return void 0;
16590
+ if (prop === "call") {
16591
+ return (operation, args, opts) => callConnector(id, operation, args, opts);
16592
+ }
16593
+ return (args, opts) => callConnector(id, prop, args, opts);
16594
+ }
16595
+ }), "connectorHandle");
16596
+ var connection = /* @__PURE__ */ __name((id) => connectorHandle(id), "connection");
16334
16597
  var R2_ENDPOINT_HOST_SUFFIX = ".r2.cloudflarestorage.com";
16335
16598
  function createS3CompatClient(options) {
16336
16599
  return new clientS3.S3Client({
@@ -16760,6 +17023,8 @@ var QueuesModule = class {
16760
17023
  this._http = _http;
16761
17024
  this._gate = gate ?? createModuleGate("queues", resolved);
16762
17025
  }
17026
+ /** @deprecated Classic v2 only. Prefer `startWorkflow(name, input)` from
17027
+ * `@stackbone/sdk/workflow` (a job → a workflow run on the World). */
16763
17028
  async publish(request) {
16764
17029
  return withGate(this._gate, async () => {
16765
17030
  const body = {
@@ -16778,6 +17043,8 @@ var QueuesModule = class {
16778
17043
  });
16779
17044
  });
16780
17045
  }
17046
+ /** @deprecated Classic v2 only. Prefer `scheduleWorkflow(name, input, cron)`
17047
+ * from `@stackbone/sdk/workflow` (a cron → a workflow run on the World). */
16781
17048
  async schedule(request) {
16782
17049
  return withGate(this._gate, async () => {
16783
17050
  const body = {
@@ -16796,6 +17063,8 @@ var QueuesModule = class {
16796
17063
  });
16797
17064
  });
16798
17065
  }
17066
+ /** @deprecated Classic v2 only. Prefer `unschedule(name)` from
17067
+ * `@stackbone/sdk/workflow`. */
16799
17068
  async unschedule(request) {
16800
17069
  return withGate(this._gate, async () => this._http.request({
16801
17070
  method: "POST",
@@ -16807,6 +17076,8 @@ var QueuesModule = class {
16807
17076
  errorMapping: ERROR_MAPPING2
16808
17077
  }));
16809
17078
  }
17079
+ /** @deprecated Classic v2 only. Prefer `listSchedules()` from
17080
+ * `@stackbone/sdk/workflow`. */
16810
17081
  async listSchedules() {
16811
17082
  return withGate(this._gate, async () => this._http.request({
16812
17083
  method: "GET",
@@ -16831,7 +17102,7 @@ var StackboneClient = class {
16831
17102
  _secrets;
16832
17103
  _config;
16833
17104
  _queues;
16834
- _connections;
17105
+ _legacyConnections;
16835
17106
  _memory;
16836
17107
  _prompts;
16837
17108
  _httpClient;
@@ -16885,16 +17156,77 @@ var StackboneClient = class {
16885
17156
  return this._queues;
16886
17157
  }
16887
17158
  /**
16888
- * Live surface — the agent's handle on the workspace's connector connections.
16889
- * `list` / `invoke` make authenticated calls to the control-plane connectors
16890
- * proxy (`/api/v1/agent/connections/*`); the credentials never enter the agent
17159
+ * Legacy surface — the agent's handle on the workspace's connector connections
17160
+ * under the OLD connector model. `list` / `invoke(connector, action, args)` make
17161
+ * authenticated calls to the control-plane connectors proxy
17162
+ * (`/api/v1/agent/connections/*`); the credentials never enter the agent
16891
17163
  * container. Gated against `connections.actions` so the handshake-blocked /
16892
17164
  * capability-missing paths are exercised the same way as the other gated
16893
17165
  * surfaces.
17166
+ *
17167
+ * Named `legacyConnections` (not `connections`) so it no longer sits one letter
17168
+ * from the new peer-free `connection(id)` entrypoint above — the two connector
17169
+ * entrypoints are now unambiguous. Behaviour is unchanged from the old
17170
+ * `connections` member.
17171
+ */
17172
+ get legacyConnections() {
17173
+ this._legacyConnections ??= new ConnectionsModule(this.resolved, this.http(), createModuleGate("connections", this.resolved, this._contractStore));
17174
+ return this._legacyConnections;
17175
+ }
17176
+ /**
17177
+ * Peer-free connector entrypoint — `stackbone.connection(id)` selects a Stackbone
17178
+ * Connect connector by its verbatim id and returns a typed handle whose generated
17179
+ * operations (`.sendMail({ ... })`, typed via the `StackboneConnections` registry)
17180
+ * and dynamic `.call(operation, args)` escape hatch both resolve to the same broker
17181
+ * call (`POST /api/connect/execute`, HMAC scheme A). It is a plain HMAC fetch — it
17182
+ * imports NO `eve` peer — so it is wired directly onto the client with no lazy
17183
+ * loading and pulls no new peer into the main barrel.
17184
+ *
17185
+ * This is the namespaced form of the top-level `connection(...)` export (now
17186
+ * `@deprecated`); both delegate to the same implementation. Distinct from the
17187
+ * plural `connections` surface above, which is the control-plane connectors proxy
17188
+ * (`list` / `invoke`).
17189
+ */
17190
+ get connection() {
17191
+ return connection;
17192
+ }
17193
+ /**
17194
+ * Namespaced sibling-agent entrypoint — `stackbone.agent(id)` selects a sibling
17195
+ * eve agent by its verbatim name and returns a lazy eve `Client`, so a workflow
17196
+ * step delegates with `stackbone.agent('support').session().send({ ... })`. The
17197
+ * name is typed against the augmentable `AgentRegistry` (declared names
17198
+ * autocomplete, a typo is a compile error).
17199
+ *
17200
+ * Peer isolation is load-bearing: selecting the agent and opening a session are
17201
+ * synchronous and import NO `eve` peer — only the session's already-async leaves
17202
+ * (`send` / `stream`) resolve `eve/client` via dynamic import on first use. So a
17203
+ * tool-only agent that imports `@stackbone/sdk` and never calls `agent(...)` never
17204
+ * eager-loads the optional `eve` peer and cannot crash-loop on a missing dep.
17205
+ *
17206
+ * This is the namespaced form of the top-level `eveAgent(...)` export (now
17207
+ * `@deprecated`) on the `@stackbone/sdk/workflow` subpath; both produce the same
17208
+ * signed workflow→agent call and the same eve `Client` API.
17209
+ */
17210
+ get agent() {
17211
+ return agent;
17212
+ }
17213
+ /**
17214
+ * Namespaced workflow trigger + schedule surface — `stackbone.workflows.start(...)`
17215
+ * / `.startAndWait(...)` / `.schedule(...)` / `.unschedule(...)` / `.listSchedules()`.
17216
+ * Start another workflow by name (fire-and-forget or durable sub-routine) and
17217
+ * manage dynamic cron triggers, all from inside a running workflow.
17218
+ *
17219
+ * These are peer-free shims over the ambient `WorkflowStarter` / `WorkflowScheduler`
17220
+ * the runtime injects on first dispatch — they import NO `workflow` / `eve` peer,
17221
+ * so (like `connection` / `agent`) they are wired directly onto the client and
17222
+ * pull nothing new into the main barrel. This is the namespaced form of the loose
17223
+ * `startWorkflow(...)` / `scheduleWorkflow(...)` exports (now `@deprecated`) on the
17224
+ * `@stackbone/sdk/workflow` subpath; both delegate to the same implementation, so
17225
+ * `start` / `startAndWait` keep their `"use step"` durability. The peer-bound
17226
+ * authoring API (`requestApproval` / `defineHook` / `sleep`) stays on that subpath.
16894
17227
  */
16895
- get connections() {
16896
- this._connections ??= new ConnectionsModule(this.resolved, this.http(), createModuleGate("connections", this.resolved, this._contractStore));
16897
- return this._connections;
17228
+ get workflows() {
17229
+ return workflows;
16898
17230
  }
16899
17231
  /**
16900
17232
  * Pending surface — runtime not built. Every method returns
@@ -17063,7 +17395,9 @@ var SDK_ERROR_CODE_PREFIXES = {
17063
17395
  "unavailable"
17064
17396
  ],
17065
17397
  /**
17066
- * `client.connections` — the agent → control plane connectors proxy. Both
17398
+ * `client.legacyConnections` — the agent → control plane connectors proxy
17399
+ * (legacy connector model). The `connections_*` code prefix stays stable (it
17400
+ * names the wire domain, not the client accessor). Both
17067
17401
  * methods (`list`, `invoke`) hit the `/api/v1/agent/connections/*` endpoints
17068
17402
  * over `HttpClient`, so the full status→domain remap (`connections_unauthorized`,
17069
17403
  * `connections_not_found`, `connections_unavailable`, …) is in play. The agent
@@ -17244,6 +17578,9 @@ function assertCapabilityShape(name, capability) {
17244
17578
  }
17245
17579
  __name(assertCapabilityShape, "assertCapabilityShape");
17246
17580
 
17581
+ // src/runtime/define-workspace.ts
17582
+ var defineWorkspace = /* @__PURE__ */ __name((workspace) => workspace, "defineWorkspace");
17583
+
17247
17584
  // src/runtime/logger.ts
17248
17585
  var writeLine = /* @__PURE__ */ __name((stream, level, msg, bindings, meta, now) => {
17249
17586
  const record = {
@@ -17281,6 +17618,37 @@ function getInvocationContext() {
17281
17618
  return storage.getStore();
17282
17619
  }
17283
17620
  __name(getInvocationContext, "getInvocationContext");
17621
+ function runWithCallerId(id, fn, options) {
17622
+ const context = {
17623
+ runId: id,
17624
+ invocationId: options?.invocationId ?? id,
17625
+ // Only attach `handler` when supplied: `exactOptionalPropertyTypes` forbids
17626
+ // an explicit `undefined` on an optional property.
17627
+ ...options?.handler !== void 0 ? {
17628
+ handler: options.handler
17629
+ } : {}
17630
+ };
17631
+ return runWithInvocationContext(context, fn);
17632
+ }
17633
+ __name(runWithCallerId, "runWithCallerId");
17634
+
17635
+ // src/runtime/ambient-client.ts
17636
+ var cached;
17637
+ function resolveAmbientClient() {
17638
+ cached ??= createClient();
17639
+ return cached;
17640
+ }
17641
+ __name(resolveAmbientClient, "resolveAmbientClient");
17642
+ var stackbone = new Proxy({}, {
17643
+ get(_target, prop) {
17644
+ const client = resolveAmbientClient();
17645
+ const value = Reflect.get(client, prop, client);
17646
+ return typeof value === "function" ? value.bind(client) : value;
17647
+ },
17648
+ has(_target, prop) {
17649
+ return Reflect.has(resolveAmbientClient(), prop);
17650
+ }
17651
+ });
17284
17652
  var patched = /* @__PURE__ */ new WeakSet();
17285
17653
  function installInvocationConsoleCapture(options = {}) {
17286
17654
  const target = options.console ?? console;
@@ -17590,13 +17958,20 @@ exports.analyzeAgentSchemas = analyzeAgentSchemas;
17590
17958
  exports.createClient = createClient;
17591
17959
  exports.createStructuredLogger = createStructuredLogger;
17592
17960
  exports.defineAgent = defineAgent;
17961
+ exports.defineWorkspace = defineWorkspace;
17593
17962
  exports.getInvocationContext = getInvocationContext;
17963
+ exports.getWorkflowScheduler = getWorkflowScheduler;
17964
+ exports.getWorkflowStarter = getWorkflowStarter;
17594
17965
  exports.installInvocationConsoleCapture = installInvocationConsoleCapture;
17595
17966
  exports.invokeRequestSchema = invokeRequestSchema;
17596
17967
  exports.isReservedErrorCode = isReservedErrorCode;
17597
17968
  exports.isSdkErrorCode = isSdkErrorCode;
17598
17969
  exports.loadSystemSecretsIntoEnv = loadSystemSecretsIntoEnv;
17599
17970
  exports.rehydrateSystemSecretsRows = rehydrateSystemSecretsRows;
17971
+ exports.runWithCallerId = runWithCallerId;
17600
17972
  exports.runWithInvocationContext = runWithInvocationContext;
17973
+ exports.setWorkflowScheduler = setWorkflowScheduler;
17974
+ exports.setWorkflowStarter = setWorkflowStarter;
17975
+ exports.stackbone = stackbone;
17601
17976
  //# sourceMappingURL=index.cjs.map
17602
17977
  //# sourceMappingURL=index.cjs.map