@skaile/workspaces 4.21.0 → 4.21.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.21.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#861](https://github.com/skaile-ai/workspaces/pull/861) [`0716bcf`](https://github.com/skaile-ai/workspaces/commit/0716bcf9c61a1238e1170aa1586974502a97857e) Thanks [@peteralbert](https://github.com/peteralbert)! - runner: a container that outlives a platform backend restart now comes through the gap intact. Agent events produced while no platform is connected are buffered (at most 10,000 events / 16 MiB, oldest dropped first) and flushed on reconnect between the replayed `session_init_ack` and the turn-status snapshot. A configured runner that tries to mint an AI credential while disconnected now fails transiently (`backend-error`) instead of terminally (`not-configured`), and each reconnect re-arms the proactive refresh scheduler. Capability calls in flight when the connection drops are rejected at once instead of waiting out their timeout. Today's platform needs no change.
8
+
3
9
  ## 4.21.0
4
10
 
5
11
  ### Minor Changes
@@ -4,7 +4,7 @@ import { findAiAssetsRoot } from './chunk-7IH3RKKK.js';
4
4
  import { WebSocketServerTransport } from './chunk-73ZXUUL6.js';
5
5
  import { assembleSystemPrompt, buildCapabilitiesPromptSection } from './chunk-W3UDISS2.js';
6
6
  import { prepareNativePolicy, codexInstanceEnvironment, parseCodexCredential, parseCodexRefreshInput, parseCodexRefreshResult } from './chunk-PE3A6FFW.js';
7
- import { resolveFlowPath } from './chunk-EJU2TOGT.js';
7
+ import { resolveFlowPath } from './chunk-SY2HSULI.js';
8
8
  import { findAiAssetsRoot as findAiAssetsRoot$1, deployCatalogEntry, undeployCatalogEntry } from './chunk-Q6NDQ6BH.js';
9
9
  import { registerBuiltinConnectors, buildConnectorPromptSection, findMissingPackages, installNpmPackages, ConnectorManager, buildSdkConnectorTools, buildLazySdkFlowTools, describeFlowOperations, buildConnectorToolDefs, buildFlowToolDefs, driveOrchestratorTurn, SessionNodeExecutor, SessionSubpromptRunner, ClassifierSubpromptRunner, SessionInlineSubFlowRunner, buildSdkFlowTools } from './chunk-ZDSZGV5F.js';
10
10
  import { loadYamlConnectorDeclarations, withMaterializedConnectorDeclarations, SecretProviderChain, ConnectorStartupError, PreMintedSecretProvider, InMemorySecretProvider, resolvedConfigToDeclarations, isKnownSecretRef, deriveSingleMaterializedConnectorDeclaration } from './chunk-MC2MF4U5.js';
@@ -3563,6 +3563,19 @@ function resolveCapabilityResult(pending, cmd) {
3563
3563
  }
3564
3564
  return true;
3565
3565
  }
3566
+ function rejectPendingCapabilityCallsOnDisconnect(pending, keep = () => false) {
3567
+ const entries = [...pending].filter(([callId]) => !keep(callId));
3568
+ for (const [callId] of entries) pending.delete(callId);
3569
+ for (const [callId, entry] of entries) {
3570
+ clearTimeout(entry.timer);
3571
+ entry.reject(
3572
+ new Error(
3573
+ `Platform connection dropped while capability call ${callId} was in flight (the platform backend may be restarting). Its outcome is unknown; retry once the platform is back if the call is safe to repeat.`
3574
+ )
3575
+ );
3576
+ }
3577
+ return entries.length;
3578
+ }
3566
3579
  function rejectCapabilityOnApprovalDeny(pending, callId, feedback) {
3567
3580
  const entry = pending.get(callId);
3568
3581
  if (!entry) return false;
@@ -4181,6 +4194,23 @@ var MINT_RETRY_MAX_DELAY_MS = 5e3;
4181
4194
  function isTransientMintFailure(code) {
4182
4195
  return code === "backend-error";
4183
4196
  }
4197
+ function aiMintPreconditionFailure(args) {
4198
+ if (args.configId === void 0) {
4199
+ return {
4200
+ ok: false,
4201
+ code: "not-configured",
4202
+ message: "no aiProviderConfigId; standalone runner cannot mediate refresh"
4203
+ };
4204
+ }
4205
+ if (!args.connected) {
4206
+ return {
4207
+ ok: false,
4208
+ code: "backend-error",
4209
+ message: "transport disconnected; the platform connection is down, refresh will be retried"
4210
+ };
4211
+ }
4212
+ return null;
4213
+ }
4184
4214
  function mintRetryDelayMs(retryNumber) {
4185
4215
  const delay = MINT_RETRY_BASE_DELAY_MS * 2 ** Math.max(0, retryNumber - 1);
4186
4216
  return Math.min(delay, MINT_RETRY_MAX_DELAY_MS);
@@ -4874,6 +4904,105 @@ async function routeReply(deps) {
4874
4904
  return "fresh-turn";
4875
4905
  }
4876
4906
 
4907
+ // runner/src/event-gap-buffer.ts
4908
+ var EVENT_GAP_BUFFER_MAX_EVENTS = 1e4;
4909
+ var EVENT_GAP_BUFFER_MAX_BYTES = 16 * 1024 * 1024;
4910
+ var UNBUFFERED_TYPES = /* @__PURE__ */ new Set([
4911
+ "session_init_ack",
4912
+ "log_entry",
4913
+ "capability_result"
4914
+ ]);
4915
+ function measure(event) {
4916
+ try {
4917
+ const json = JSON.stringify(event);
4918
+ return json === void 0 ? 0 : Buffer.byteLength(json, "utf8");
4919
+ } catch {
4920
+ return 0;
4921
+ }
4922
+ }
4923
+ var EventGapBuffer = class _EventGapBuffer {
4924
+ maxEvents;
4925
+ maxBytes;
4926
+ entries = [];
4927
+ /** Index of the oldest live entry; eviction advances it instead of shifting the array. */
4928
+ head = 0;
4929
+ bytes = 0;
4930
+ dropped = 0;
4931
+ constructor(opts = {}) {
4932
+ this.maxEvents = opts.maxEvents ?? EVENT_GAP_BUFFER_MAX_EVENTS;
4933
+ this.maxBytes = opts.maxBytes ?? EVENT_GAP_BUFFER_MAX_BYTES;
4934
+ }
4935
+ /** Number of events currently held. */
4936
+ get size() {
4937
+ return this.entries.length - this.head;
4938
+ }
4939
+ /** Whether a drain would report anything (held events or drops). */
4940
+ get hasPending() {
4941
+ return this.size > 0 || this.dropped > 0;
4942
+ }
4943
+ /** The callIds of the `capability_invoked` events currently held. */
4944
+ heldCapabilityCallIds() {
4945
+ const ids = /* @__PURE__ */ new Set();
4946
+ for (let i = this.head; i < this.entries.length; i++) {
4947
+ const event = this.entries[i]?.event;
4948
+ if (event?.type === "capability_invoked") ids.add(event.callId);
4949
+ }
4950
+ return ids;
4951
+ }
4952
+ /** Whether {@link push} would hold this event type at all. */
4953
+ static accepts(event) {
4954
+ return !UNBUFFERED_TYPES.has(event.type);
4955
+ }
4956
+ /**
4957
+ * Append an event, evicting the oldest past either cap. An event larger than
4958
+ * the byte cap on its own is counted as dropped and not held.
4959
+ */
4960
+ push(event, opts = {}) {
4961
+ if (!_EventGapBuffer.accepts(event)) return;
4962
+ const bytes = measure(event);
4963
+ if (bytes > this.maxBytes) {
4964
+ this.dropped += 1;
4965
+ return;
4966
+ }
4967
+ this.entries.push({ event, bytes, ...opts.isStale ? { isStale: opts.isStale } : {} });
4968
+ this.bytes += bytes;
4969
+ while (this.size > this.maxEvents || this.bytes > this.maxBytes) {
4970
+ const oldest = this.entries[this.head];
4971
+ if (!oldest) break;
4972
+ this.head += 1;
4973
+ this.bytes -= oldest.bytes;
4974
+ this.dropped += 1;
4975
+ }
4976
+ if (this.head > 1024 && this.head * 2 > this.entries.length) {
4977
+ this.entries = this.entries.slice(this.head);
4978
+ this.head = 0;
4979
+ }
4980
+ }
4981
+ /** Hand back everything held, oldest first, and reset. */
4982
+ drain() {
4983
+ const events = [];
4984
+ let stale = 0;
4985
+ for (let i = this.head; i < this.entries.length; i++) {
4986
+ const entry = this.entries[i];
4987
+ if (!entry) continue;
4988
+ if (entry.isStale?.()) stale += 1;
4989
+ else events.push(entry.event);
4990
+ }
4991
+ const dropped = this.dropped;
4992
+ this.clear();
4993
+ return { events, dropped, stale };
4994
+ }
4995
+ /** Discard everything held. Returns how many events were discarded. */
4996
+ clear() {
4997
+ const discarded = this.size;
4998
+ this.entries = [];
4999
+ this.head = 0;
5000
+ this.bytes = 0;
5001
+ this.dropped = 0;
5002
+ return discarded;
5003
+ }
5004
+ };
5005
+
4877
5006
  // runner/src/compaction/prompt.ts
4878
5007
  var DEFAULT_COMPACTION_PROMPT = `You are being asked to compact this conversation into a structured summary.
4879
5008
  This summary will replace the full conversation history when the session
@@ -6184,8 +6313,8 @@ var ContextUsageCollector = class {
6184
6313
  if (opts.measure && driver?.getContextUsageReport) {
6185
6314
  try {
6186
6315
  const detail = opts.measure;
6187
- const measure = driver.getContextUsageReport.bind(driver);
6188
- report = await this.sharedMeasurement(detail, () => measure({ detail }));
6316
+ const measure2 = driver.getContextUsageReport.bind(driver);
6317
+ report = await this.sharedMeasurement(detail, () => measure2({ detail }));
6189
6318
  if (report) {
6190
6319
  this.lastReport = report;
6191
6320
  reportFresh = true;
@@ -6222,11 +6351,11 @@ var ContextUsageCollector = class {
6222
6351
  * lands while a `full` count is running (two panels, a double click) shares
6223
6352
  * it instead of paying for another round of `count_tokens` calls.
6224
6353
  */
6225
- sharedMeasurement(detail, measure) {
6354
+ sharedMeasurement(detail, measure2) {
6226
6355
  const running = this.inflight.get(detail);
6227
6356
  if (running) return running;
6228
6357
  const measurement = withTimeout(
6229
- measure(),
6358
+ measure2(),
6230
6359
  this.deps.measureTimeoutMs ?? DEFAULT_MEASURE_TIMEOUT_MS
6231
6360
  ).finally(() => {
6232
6361
  if (this.inflight.get(detail) === measurement) this.inflight.delete(detail);
@@ -7814,11 +7943,21 @@ async function startAgentServer(opts) {
7814
7943
  })
7815
7944
  );
7816
7945
  const turnStatus = new TurnStatusTracker();
7946
+ const eventGapBuffer = new EventGapBuffer();
7817
7947
  function sendEvent(event) {
7818
7948
  turnStatus.observe(event);
7819
7949
  if (transport.connected) {
7820
7950
  transport.send(event);
7951
+ return;
7821
7952
  }
7953
+ if (!initAcknowledged) return;
7954
+ eventGapBuffer.push(event, { isStale: settledCapabilityCallCheck(event) });
7955
+ }
7956
+ function settledCapabilityCallCheck(event) {
7957
+ if (event.type !== "capability_invoked") return void 0;
7958
+ const { callId } = event;
7959
+ if (!pendingCapabilityCalls.has(callId)) return void 0;
7960
+ return () => !pendingCapabilityCalls.has(callId);
7822
7961
  }
7823
7962
  let initAcknowledged = false;
7824
7963
  let initGeneration = 0;
@@ -7836,6 +7975,20 @@ async function startAgentServer(opts) {
7836
7975
  bootstrapCapabilityRegistry(capabilityRegistry);
7837
7976
  const hostRuntimeCapabilities = /* @__PURE__ */ new Set();
7838
7977
  const pendingCapabilityCalls = /* @__PURE__ */ new Map();
7978
+ function rejectCallsSentToPreviousPeer(trigger) {
7979
+ const unsent = eventGapBuffer.heldCapabilityCallIds();
7980
+ const rejected = rejectPendingCapabilityCallsOnDisconnect(
7981
+ pendingCapabilityCalls,
7982
+ (callId) => unsent.has(callId)
7983
+ );
7984
+ if (rejected > 0) {
7985
+ serverLog.warn(
7986
+ `[serve] platform connection dropped (${trigger}); rejected ${rejected} in-flight capability call(s)`
7987
+ );
7988
+ }
7989
+ }
7990
+ transport.onDisconnect(() => rejectCallsSentToPreviousPeer("disconnect"));
7991
+ transport.onConnect(() => rejectCallsSentToPreviousPeer("replaced connection"));
7839
7992
  const remoteCapabilityInvoker = (name, input, timeoutMs, signal) => {
7840
7993
  const callId = typeof crypto?.randomUUID === "function" ? crypto.randomUUID() : `rcap-${Date.now()}-${Math.floor(Math.random() * 1e9)}`;
7841
7994
  return new Promise((resolve4, reject) => {
@@ -7878,13 +8031,11 @@ async function startAgentServer(opts) {
7878
8031
  t.unref?.();
7879
8032
  });
7880
8033
  async function mintAndPersistAiCredential(args) {
7881
- if (!transport.connected || aiProviderConfigId === void 0) {
7882
- return {
7883
- ok: false,
7884
- code: "not-configured",
7885
- message: "no transport or aiProviderConfigId; standalone runner cannot mediate refresh"
7886
- };
7887
- }
8034
+ const precondition = aiMintPreconditionFailure({
8035
+ connected: transport.connected,
8036
+ configId: aiProviderConfigId
8037
+ });
8038
+ if (precondition) return precondition;
7888
8039
  const targetConfigId = args.configId || aiProviderConfigId;
7889
8040
  try {
7890
8041
  const home = process.env.HOME || homedir();
@@ -8824,6 +8975,7 @@ async function startAgentServer(opts) {
8824
8975
  async function cleanup() {
8825
8976
  if (managedHost) managedBootstrapClosed = true;
8826
8977
  initAcknowledged = false;
8978
+ eventGapBuffer.clear();
8827
8979
  try {
8828
8980
  await Promise.race([
8829
8981
  sessionReady,
@@ -9994,9 +10146,28 @@ async function startAgentServer(opts) {
9994
10146
  replayed: true
9995
10147
  });
9996
10148
  });
10149
+ transport.onConnect(() => {
10150
+ if (!eventGapBuffer.hasPending) return;
10151
+ if (!initAcknowledged || sessionReadyOutcome === "rejected") {
10152
+ const discarded = eventGapBuffer.clear();
10153
+ serverLog.warn(
10154
+ `[serve] discarded ${discarded} event(s) buffered while disconnected: the init they belong to is no longer acknowledged`
10155
+ );
10156
+ return;
10157
+ }
10158
+ const { events, dropped, stale } = eventGapBuffer.drain();
10159
+ for (const event of events) transport.send(event);
10160
+ serverLog.warn(
10161
+ `[serve] flushed ${events.length} event(s) buffered while the platform was disconnected; dropped ${dropped} over the buffer cap, withheld ${stale} settled capability call(s)`
10162
+ );
10163
+ });
9997
10164
  transport.onConnect(() => {
9998
10165
  sendEvent(turnStatus.snapshot());
9999
10166
  });
10167
+ transport.onConnect(() => {
10168
+ if (!initAcknowledged || managedCodex || aiProviderConfigId === void 0) return;
10169
+ aiCredentialRefreshScheduler.ensureArmed();
10170
+ });
10000
10171
  transport.onConnect(() => {
10001
10172
  if (managedHost && !managedBootstrapClosed)
10002
10173
  sendEvent({
@@ -10211,6 +10382,6 @@ function touchSession(state) {
10211
10382
  return { ...state, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
10212
10383
  }
10213
10384
 
10214
- export { CLAUDE_CODE_CREDENTIALS_KEY, COMPILE_MANIFEST_FILENAME, CapabilityRegistry, DEFAULT_CAPABILITY_CALL_TIMEOUT_MS, DEFAULT_COALESCE_MS, DEFAULT_FLOW_MUTATE_CONNECTOR_WAIT_MS, MOUNT_LIST_MAX_DEPTH, MOUNT_LIST_MAX_ENTRIES, MOUNT_READ_DEADLINE_FACTOR, MOUNT_STAT_BUDGET_MS, MOUNT_STAT_MAX_ENTRIES, MOUNT_TREE_OP_DEADLINE_FACTOR, MarkdownStreamer, PreInitRingSink, ResourceOperationError, SESSION_ROOT_WRITABLE_DIRS, SESSION_ROOT_WRITABLE_FILES, WS_AUTH_TOKEN_ENV, WS_AUTH_TOKEN_FILE_ENV, agentDefinitionExists, bootstrapCapabilityRegistry, bootstrapRunnerLogStore, buildAgentResources, buildClientCapabilityHandler, buildConnectorTokenMediator, buildContextSection, buildEnvironmentSection, buildResourcesAvailablePayload, buildStoreSnapshotReplay, builtinCapabilities, capabilityLogInstance, clearPreInitRingSink, clearSession, compileComposition, computeCapabilitySignature, computeDirectoryTotals, connectorRefreshKind, createAgentSession, createFlowConnectorReadiness, createManagedCodexSubpromptDriver, createSessionStimulusBus, defineCapability, deleteSession, dispatchResourceRequest, dispatchRunnerCapabilityInvocation, emitSystemPromptComposed, ensureClaudeSettingsDisablesConnectors, ensureGitConfigInclude, executeConnectorMutate, extractClaudeAiOauthExpiresAt, flowStartNeedsDriverRestart, getPreInitRingSink, handleMountResourceRequest, handleResourceRequest, handleSessionRootResourceRequest, hasNonTerminalFlow, hostOpResumeStimulus, installPreInitRingSink, isSessionRootPathAllowed, isTerminalFlowStatus, listSessions, loadAgentManifest, loadCompileManifest, loadCompileManifestFromDir, loadManagedCodexHostConfig, loadSession, loadSessionById, mcpAuthSecretKey, newSession, nulTailPaddingLength, pickFlowToolTarget, pickRepointedManager, planFlowMutate, prepareCodexTools, reconcilePendingDecisions, registerActiveFlow, registerCompositionCapabilities, rejectCapabilityOnApprovalDeny, resetRunnerLogStore, resolveAgentComposition, resolveAgentMixins, resolveBinding, resolveCapabilityCallTimeoutMs, resolveCapabilityResult, resolveComposition, resolveFlowMutateConnectorWaitMs, resolveMixin, runAgentChat, saveSession, setCurrentSession, setUpFlowConnector, startAgentServer, stimulusFromMetas, supportsLiveToolUpdates, takeRunnerWsAuthToken, touchSession, validateInputResponse, writeClaudeCodeCredentialsFile };
10215
- //# sourceMappingURL=chunk-ZJEQFNKE.js.map
10216
- //# sourceMappingURL=chunk-ZJEQFNKE.js.map
10385
+ export { CLAUDE_CODE_CREDENTIALS_KEY, COMPILE_MANIFEST_FILENAME, CapabilityRegistry, DEFAULT_CAPABILITY_CALL_TIMEOUT_MS, DEFAULT_COALESCE_MS, DEFAULT_FLOW_MUTATE_CONNECTOR_WAIT_MS, MOUNT_LIST_MAX_DEPTH, MOUNT_LIST_MAX_ENTRIES, MOUNT_READ_DEADLINE_FACTOR, MOUNT_STAT_BUDGET_MS, MOUNT_STAT_MAX_ENTRIES, MOUNT_TREE_OP_DEADLINE_FACTOR, MarkdownStreamer, PreInitRingSink, ResourceOperationError, SESSION_ROOT_WRITABLE_DIRS, SESSION_ROOT_WRITABLE_FILES, WS_AUTH_TOKEN_ENV, WS_AUTH_TOKEN_FILE_ENV, agentDefinitionExists, bootstrapCapabilityRegistry, bootstrapRunnerLogStore, buildAgentResources, buildClientCapabilityHandler, buildConnectorTokenMediator, buildContextSection, buildEnvironmentSection, buildResourcesAvailablePayload, buildStoreSnapshotReplay, builtinCapabilities, capabilityLogInstance, clearPreInitRingSink, clearSession, compileComposition, computeCapabilitySignature, computeDirectoryTotals, connectorRefreshKind, createAgentSession, createFlowConnectorReadiness, createManagedCodexSubpromptDriver, createSessionStimulusBus, defineCapability, deleteSession, dispatchResourceRequest, dispatchRunnerCapabilityInvocation, emitSystemPromptComposed, ensureClaudeSettingsDisablesConnectors, ensureGitConfigInclude, executeConnectorMutate, extractClaudeAiOauthExpiresAt, flowStartNeedsDriverRestart, getPreInitRingSink, handleMountResourceRequest, handleResourceRequest, handleSessionRootResourceRequest, hasNonTerminalFlow, hostOpResumeStimulus, installPreInitRingSink, isSessionRootPathAllowed, isTerminalFlowStatus, listSessions, loadAgentManifest, loadCompileManifest, loadCompileManifestFromDir, loadManagedCodexHostConfig, loadSession, loadSessionById, mcpAuthSecretKey, newSession, nulTailPaddingLength, pickFlowToolTarget, pickRepointedManager, planFlowMutate, prepareCodexTools, reconcilePendingDecisions, registerActiveFlow, registerCompositionCapabilities, rejectCapabilityOnApprovalDeny, rejectPendingCapabilityCallsOnDisconnect, resetRunnerLogStore, resolveAgentComposition, resolveAgentMixins, resolveBinding, resolveCapabilityCallTimeoutMs, resolveCapabilityResult, resolveComposition, resolveFlowMutateConnectorWaitMs, resolveMixin, runAgentChat, saveSession, setCurrentSession, setUpFlowConnector, startAgentServer, stimulusFromMetas, supportsLiveToolUpdates, takeRunnerWsAuthToken, touchSession, validateInputResponse, writeClaudeCodeCredentialsFile };
10386
+ //# sourceMappingURL=chunk-N5XNEKHC.js.map
10387
+ //# sourceMappingURL=chunk-N5XNEKHC.js.map