@stacklink/sdk 0.3.14 → 0.4.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.
@@ -1,7 +1,7 @@
1
1
  import { botApiSignaturePayload } from '../domain/bot-contract.js';
2
2
  import { materializeStacklinkWorkbenchExecutionResponse, } from '../domain/stacklink-meta-tools.js';
3
3
  export { StacklinkMemoryLifecycle, StacklinkMemoryLifecycleError, createStacklinkMemoryLifecycle, serializeCompletedConversationTurn, } from './memory-lifecycle.js';
4
- export const stacklinkTypeScriptSdkVersion = '0.3.14';
4
+ export const stacklinkTypeScriptSdkVersion = '0.4.0';
5
5
  const workbenchReusableRunComparisonWaitMs = 120_000;
6
6
  const workbenchReusableRunComparisonPollMs = 1_000;
7
7
  export class StacklinkApiError extends Error {
@@ -9,12 +9,14 @@ export class StacklinkApiError extends Error {
9
9
  code;
10
10
  details;
11
11
  retryAfterMs;
12
- constructor(message, statusCode, code, details, retryAfterMs) {
12
+ failureId;
13
+ constructor(message, statusCode, code, details, retryAfterMs, failureId) {
13
14
  super(message);
14
15
  this.statusCode = statusCode;
15
16
  this.code = code;
16
17
  this.details = details;
17
18
  this.retryAfterMs = retryAfterMs;
19
+ this.failureId = failureId;
18
20
  this.name = 'StacklinkApiError';
19
21
  }
20
22
  }
@@ -540,6 +542,9 @@ export class Stacklink {
540
542
  body: input,
541
543
  });
542
544
  }
545
+ async resumeWorkbenchExecution(input, options = {}) {
546
+ return this.request('/v1/workbench/resume', { method: 'POST', body: input, signal: options.signal });
547
+ }
543
548
  async workbenchModels() {
544
549
  return this.request('/v1/workbench/models');
545
550
  }
@@ -550,6 +555,11 @@ export class Stacklink {
550
555
  signal: options.signal,
551
556
  });
552
557
  this.attachAbortSignalCancellation(input, response, options.signal);
558
+ if (isSdkRecord(response.operation) && typeof response.operation.operationId === 'string' && typeof response.operation.workbenchSessionId === 'string' && typeof input.sessionId === 'string') {
559
+ const { operation, ...accepted } = response;
560
+ const completed = await this.waitForWorkbenchOperation({ sessionId: input.sessionId, workbenchSessionId: response.operation.workbenchSessionId, operationId: response.operation.operationId }, options);
561
+ return { ...accepted, ...completed };
562
+ }
553
563
  if (input.operation === 'run_code' && input.background !== true) {
554
564
  return this.waitForWorkbenchResponse(input, response, options);
555
565
  }
@@ -561,35 +571,83 @@ export class Stacklink {
561
571
  body: input,
562
572
  });
563
573
  }
564
- async deleteWorkbenchSession(input) {
565
- return this.request(`/v1/workbench/sessions/${input.workbenchSessionId}`, {
566
- method: 'DELETE',
567
- query: { sessionId: input.sessionId },
574
+ async getWorkbenchOperation(input, options = {}) {
575
+ return this.request(`/v1/workbench/sessions/${input.workbenchSessionId}/operations/${input.operationId}`, { query: { sessionId: input.sessionId }, ...options });
576
+ }
577
+ async waitForWorkbenchOperation(input, options = {}) {
578
+ const deadline = Date.now() + (options.timeoutMs ?? 300_000);
579
+ while (Date.now() < deadline) {
580
+ options.signal?.throwIfAborted();
581
+ let operation;
582
+ try {
583
+ ({ operation } = await this.getWorkbenchOperation(input, { signal: options.signal, timeoutMs: Math.min(15_000, Math.max(1, deadline - Date.now())) }));
584
+ }
585
+ catch (error) {
586
+ throw new StacklinkApiError('Observation stopped. Resume the same Workbench operation.', error instanceof StacklinkApiError ? error.statusCode : 408, 'workbench_operation_observation_stopped', { ...input, cause: error instanceof StacklinkApiError ? error.code : undefined });
587
+ }
588
+ if (operation.status === 'completed')
589
+ return operation.result;
590
+ if (operation.status === 'failed')
591
+ throw new StacklinkApiError('The Workbench operation needs attention.', 409, 'workbench_operation_failed', { ...input, operation });
592
+ const delayMs = Math.min(Math.max(100, operation.retryAfterMs), Math.max(0, deadline - Date.now()));
593
+ await new Promise((resolve, reject) => {
594
+ const abort = () => { clearTimeout(timer); reject(options.signal?.reason); };
595
+ const timer = setTimeout(() => { options.signal?.removeEventListener('abort', abort); resolve(); }, delayMs);
596
+ options.signal?.addEventListener('abort', abort, { once: true });
597
+ });
598
+ }
599
+ throw new StacklinkApiError('The Workbench operation is still running. Resume with its operation ID.', 408, 'workbench_operation_pending', input);
600
+ }
601
+ async deleteWorkbenchSession(input, options = {}) {
602
+ const result = await this.request(`/v1/workbench/sessions/${input.workbenchSessionId}`, {
603
+ method: 'DELETE', query: { sessionId: input.sessionId }, signal: options.signal,
568
604
  });
605
+ return result.deleted ? result : this.waitForWorkbenchOperation({ ...input, operationId: result.operation.operationId }, options);
569
606
  }
570
607
  async listWorkbenchFiles(input) {
571
- return this.request(`/v1/workbench/sessions/${input.workbenchSessionId}/files`, { query: { sessionId: input.sessionId } });
608
+ return this.request(`/v1/workbench/sessions/${input.workbenchSessionId}/files`, { query: { sessionId: input.sessionId, cursor: input.cursor, limit: input.limit } });
572
609
  }
573
610
  async readWorkbenchFile(input) {
574
611
  return this.request(`/v1/workbench/sessions/${input.workbenchSessionId}/files`, { query: { sessionId: input.sessionId, path: input.path } });
575
612
  }
576
613
  async uploadWorkbenchFile(input) {
577
- return this.request(`/v1/workbench/sessions/${input.workbenchSessionId}/files`, {
578
- method: 'PUT',
579
- body: {
580
- sessionId: input.sessionId,
581
- path: input.path,
582
- contentBase64: base64Encode(typeof input.content === 'string' ? utf8(input.content) : input.content),
583
- contentType: input.contentType,
584
- metadata: input.metadata,
585
- },
586
- });
614
+ const uploadId = input.uploadId ?? crypto.randomUUID();
615
+ try {
616
+ const result = await this.request(`/v1/workbench/sessions/${input.workbenchSessionId}/files`, {
617
+ method: 'PUT',
618
+ body: {
619
+ sessionId: input.sessionId,
620
+ uploadId,
621
+ path: input.path,
622
+ contentBase64: base64Encode(typeof input.content === 'string' ? utf8(input.content) : input.content),
623
+ contentType: input.contentType,
624
+ metadata: input.metadata,
625
+ },
626
+ });
627
+ return ('file' in result) ? result : await this.waitForWorkbenchOperation({ sessionId: input.sessionId, workbenchSessionId: input.workbenchSessionId, operationId: result.operation.operationId });
628
+ }
629
+ catch (error) {
630
+ if (error instanceof StacklinkApiError)
631
+ throw new StacklinkApiError(error.message, error.statusCode, error.code, { ...isSdkRecord(error.details) ? error.details : {}, uploadId, workbenchSessionId: input.workbenchSessionId, sessionId: input.sessionId }, error.retryAfterMs, error.failureId);
632
+ throw error;
633
+ }
587
634
  }
588
635
  async prepareWorkbenchFileUpload(input) {
589
- return this.request(`/v1/workbench/sessions/${input.workbenchSessionId}/files/upload-url`, { method: 'POST', body: input });
636
+ const { workbenchSessionId, ...body } = input;
637
+ const uploadId = input.uploadId ?? crypto.randomUUID();
638
+ try {
639
+ return await this.request(`/v1/workbench/sessions/${workbenchSessionId}/files/upload-url`, { method: 'POST', body: { ...body, uploadId } });
640
+ }
641
+ catch (error) {
642
+ if (error instanceof StacklinkApiError)
643
+ throw new StacklinkApiError(error.message, error.statusCode, error.code, { ...isSdkRecord(error.details) ? error.details : {}, uploadId, workbenchSessionId, sessionId: input.sessionId }, error.retryAfterMs, error.failureId);
644
+ throw error;
645
+ }
590
646
  }
591
- async finalizeWorkbenchFileUpload(input) {
592
- return this.request(`/v1/workbench/sessions/${input.workbenchSessionId}/files/finalize-upload`, { method: 'POST', body: input });
647
+ async finalizeWorkbenchFileUpload(input, options = {}) {
648
+ const { workbenchSessionId, ...body } = input;
649
+ const result = await this.request(`/v1/workbench/sessions/${workbenchSessionId}/files/finalize-upload`, { method: 'POST', body, signal: options.signal });
650
+ return ('file' in result) ? result : this.waitForWorkbenchOperation({ sessionId: input.sessionId, workbenchSessionId, operationId: result.operation.operationId }, options);
593
651
  }
594
652
  async uploadWorkbenchFileDirect(input) {
595
653
  const content = typeof input.content === 'string' ? utf8(input.content) : input.content;
@@ -599,15 +657,23 @@ export class Stacklink {
599
657
  workbenchSessionId: input.workbenchSessionId,
600
658
  path: input.path,
601
659
  contentType,
602
- sizeBytes: content.byteLength,
603
- });
604
- const response = await this.fetchImpl(prepared.upload.uploadUrl, {
605
- method: 'PUT',
606
- headers: prepared.upload.requiredHeaders,
607
- body: content,
660
+ sizeBytes: content instanceof Blob ? content.size : content.byteLength,
661
+ uploadId: input.uploadId ?? crypto.randomUUID(),
608
662
  });
609
- if (!response.ok) {
610
- throw new StacklinkApiError(`Workbench file upload failed with ${response.status}`, response.status, 'workbench_file_direct_upload_failed');
663
+ let response;
664
+ try {
665
+ response = await this.fetchImpl(prepared.upload.uploadUrl, {
666
+ method: 'PUT',
667
+ headers: prepared.upload.requiredHeaders,
668
+ body: content,
669
+ signal: input.signal ? AbortSignal.any([input.signal, AbortSignal.timeout(input.transferTimeoutMs ?? 300_000)]) : AbortSignal.timeout(input.transferTimeoutMs ?? 300_000),
670
+ });
671
+ }
672
+ catch (error) {
673
+ throw new StacklinkApiError("Upload outcome is unknown. Finalize the same uploadId to reconcile; do not create another upload.", 408, "workbench_upload_outcome_unknown", { uploadId: prepared.upload.uploadId, workbenchSessionId: input.workbenchSessionId, sessionId: input.sessionId });
674
+ }
675
+ if (!response.ok && response.status !== 412) {
676
+ throw new StacklinkApiError(`Workbench file upload failed with ${response.status}`, response.status, 'workbench_file_direct_upload_failed', { uploadId: prepared.upload.uploadId, workbenchSessionId: input.workbenchSessionId, sessionId: input.sessionId });
611
677
  }
612
678
  return this.finalizeWorkbenchFileUpload({
613
679
  sessionId: input.sessionId,
@@ -621,7 +687,7 @@ export class Stacklink {
621
687
  }
622
688
  async downloadWorkbenchFile(input) {
623
689
  const signed = await this.getWorkbenchFileDownload(input);
624
- const response = await this.fetchImpl(signed.downloadUrl);
690
+ const response = await this.fetchImpl(signed.downloadUrl, { headers: signed.requiredHeaders ?? {}, signal: AbortSignal.timeout(300_000) });
625
691
  if (!response.ok) {
626
692
  throw new StacklinkApiError(`Workbench file download failed with ${response.status}`, response.status, 'workbench_file_download_failed');
627
693
  }
@@ -712,6 +778,9 @@ export class Stacklink {
712
778
  async rollbackWorkbenchRunDefinition(input) {
713
779
  return this.request(`/v1/workbench/run-definitions/${input.runDefinitionId}/rollback`, { method: 'POST', body: { sessionId: input.sessionId, expectedPublishedVersion: input.expectedPublishedVersion } });
714
780
  }
781
+ async getWorkbenchComputeStatus(input, options = {}) {
782
+ return this.request('/v1/workbench/run', { method: 'POST', body: { ...input, operation: 'compute_status' }, signal: options.signal });
783
+ }
715
784
  async destroyWorkbenchSession(input, options = {}) {
716
785
  return this.runWorkbench({
717
786
  sessionId: input.sessionId,
@@ -737,7 +806,7 @@ export class Stacklink {
737
806
  const executionKind = accepted.executionKind === 'workbench_code' || accepted.executionKind === 'workbench_bash'
738
807
  ? accepted.executionKind
739
808
  : undefined;
740
- if (!sessionId || !executionId || !executionKind || accepted.status === 'waiting_for_approval')
809
+ if (!sessionId || !executionId || !executionKind || ['waiting_for_approval', 'waiting_saved', 'waiting_ready'].includes(String(accepted.status)))
741
810
  return accepted;
742
811
  while (true) {
743
812
  const waited = await this.waitForExecution({
@@ -747,7 +816,7 @@ export class Stacklink {
747
816
  waitTimeoutMs: 10_000,
748
817
  }, options);
749
818
  const execution = isSdkRecord(waited.execution) ? waited.execution : undefined;
750
- if (execution && (isTerminalSdkExecution(execution) || execution.status === 'waiting_for_approval')) {
819
+ if (execution && (isTerminalSdkExecution(execution) || execution.nextAction === 'wait_for_approval' || ['waiting_for_approval', 'waiting_saved', 'waiting_ready'].includes(String(execution.status)))) {
751
820
  return materializeStacklinkWorkbenchExecutionResponse(accepted, execution);
752
821
  }
753
822
  }
@@ -1187,10 +1256,21 @@ export class Stacklink {
1187
1256
  return this.requestRaw(`/v1/workbench/artifacts/${artifactId}/download`);
1188
1257
  }
1189
1258
  async promoteWorkbenchArtifact(input) {
1190
- return this.request('/v1/workbench/artifacts', {
1191
- method: 'POST',
1192
- body: input,
1193
- });
1259
+ const artifactRef = input.artifactRef ?? `wba_${crypto.randomUUID()}`;
1260
+ try {
1261
+ const result = await this.request('/v1/workbench/artifacts', {
1262
+ method: 'POST',
1263
+ body: { ...input, artifactRef },
1264
+ });
1265
+ if (!result.operation)
1266
+ return result;
1267
+ return await this.waitForWorkbenchOperation({ sessionId: input.sessionId, workbenchSessionId: input.workbenchSessionId, operationId: result.operation.operationId });
1268
+ }
1269
+ catch (error) {
1270
+ if (error instanceof StacklinkApiError)
1271
+ throw new StacklinkApiError(error.message, error.statusCode, error.code, { ...isSdkRecord(error.details) ? error.details : {}, artifactRef, workbenchSessionId: input.workbenchSessionId, sessionId: input.sessionId }, error.retryAfterMs, error.failureId);
1272
+ throw error;
1273
+ }
1194
1274
  }
1195
1275
  async deleteWorkbenchArtifact(input) {
1196
1276
  return this.request(`/v1/workbench/artifacts/${input.artifactId}`, {
@@ -1491,7 +1571,7 @@ export class Stacklink {
1491
1571
  const details = body && typeof body === 'object' && 'details' in body
1492
1572
  ? body.details
1493
1573
  : undefined;
1494
- throw new StacklinkApiError(message, response.status, code, details);
1574
+ throw new StacklinkApiError(message, response.status, code, details, undefined, response.headers.get('x-stacklink-failure-id') ?? (isSdkRecord(body) && typeof body.failureId === 'string' ? body.failureId : undefined));
1495
1575
  }
1496
1576
  return body;
1497
1577
  }
@@ -1506,7 +1586,7 @@ export class Stacklink {
1506
1586
  catch {
1507
1587
  parsed = null;
1508
1588
  }
1509
- throw new StacklinkApiError(isSdkRecord(parsed) && typeof parsed.message === 'string' ? parsed.message : `Stacklink request failed with ${response.status}`, response.status, isSdkRecord(parsed) && typeof parsed.code === 'string' ? parsed.code : undefined, isSdkRecord(parsed) ? parsed.details : undefined, response.headers.has('retry-after') ? sdkRetryDelayMs(response, 1) : undefined);
1589
+ throw new StacklinkApiError(isSdkRecord(parsed) && typeof parsed.message === 'string' ? parsed.message : `Stacklink request failed with ${response.status}`, response.status, isSdkRecord(parsed) && typeof parsed.code === 'string' ? parsed.code : undefined, isSdkRecord(parsed) ? parsed.details : undefined, response.headers.has('retry-after') ? sdkRetryDelayMs(response, 1) : undefined, response.headers.get('x-stacklink-failure-id') ?? undefined);
1510
1590
  }
1511
1591
  return response;
1512
1592
  }
@@ -1769,6 +1849,7 @@ export class Stacklink {
1769
1849
  ...extraHeaders,
1770
1850
  'x-stacklink-client-channel': 'ts_sdk',
1771
1851
  'x-stacklink-client-name': 'stacklink-ts',
1852
+ 'x-stacklink-workbench-protocol': '2',
1772
1853
  'x-stacklink-client-version': stacklinkTypeScriptSdkVersion,
1773
1854
  };
1774
1855
  }
@@ -1778,6 +1859,7 @@ export class Stacklink {
1778
1859
  ...extraHeaders,
1779
1860
  'x-stacklink-client-channel': 'ts_sdk',
1780
1861
  'x-stacklink-client-name': 'stacklink-ts',
1862
+ 'x-stacklink-workbench-protocol': '2',
1781
1863
  'x-stacklink-client-version': stacklinkTypeScriptSdkVersion,
1782
1864
  };
1783
1865
  }
@@ -2453,8 +2535,9 @@ export class StacklinkWorkbenchFiles {
2453
2535
  this.platformSessionId = platformSessionId;
2454
2536
  this.workbenchSessionId = workbenchSessionId;
2455
2537
  }
2456
- async list() {
2538
+ async list(options = {}) {
2457
2539
  return this.client.listWorkbenchFiles({
2540
+ ...options,
2458
2541
  sessionId: this.platformSessionId,
2459
2542
  workbenchSessionId: await this.workbenchSessionId(),
2460
2543
  });
@@ -2603,6 +2686,9 @@ export class StacklinkSessionSandbox {
2603
2686
  this.runs = new StacklinkWorkbenchRuns(client, platformSessionId, () => this.ensureWorkbenchSession());
2604
2687
  this.artifacts = new StacklinkWorkbenchArtifacts(client, platformSessionId, () => this.ensureWorkbenchSession());
2605
2688
  }
2689
+ resume(executionId, expectedWaitRevision, checkpointId) {
2690
+ return this.client.resumeWorkbenchExecution({ sessionId: this.platformSessionId, executionId, expectedWaitRevision, checkpointId });
2691
+ }
2606
2692
  async use(workbenchSessionId, input = {}) {
2607
2693
  const response = await this.client.useWorkbenchSession({
2608
2694
  sessionId: this.platformSessionId,
@@ -3118,7 +3204,7 @@ function unwrapMcpToolResult(response) {
3118
3204
  const code = typeof response.error.code === 'string' || typeof response.error.code === 'number'
3119
3205
  ? String(response.error.code)
3120
3206
  : undefined;
3121
- throw new StacklinkApiError(message, 400, code, response.error.data);
3207
+ throw new StacklinkApiError(message, 400, code, response.error.data, undefined, isSdkRecord(response.error.data) && typeof response.error.data.failureId === 'string' ? response.error.data.failureId : undefined);
3122
3208
  }
3123
3209
  const result = response.result;
3124
3210
  if (!isSdkRecord(result))
@@ -3131,7 +3217,8 @@ function unwrapMcpToolResult(response) {
3131
3217
  .map((item) => String(item.text))
3132
3218
  .join('\n')
3133
3219
  : '';
3134
- throw new StacklinkApiError(errorText || 'Stacklink MCP tool call failed.', 400, 'mcp_tool_error', result);
3220
+ const failure = isSdkRecord(result.structuredContent) && isSdkRecord(result.structuredContent.error) ? result.structuredContent.error : undefined;
3221
+ throw new StacklinkApiError(errorText || 'Stacklink MCP tool call failed.', 400, 'mcp_tool_error', result, undefined, typeof failure?.failureId === 'string' ? failure.failureId : undefined);
3135
3222
  }
3136
3223
  if ('structuredContent' in result)
3137
3224
  return result.structuredContent;
@@ -3195,7 +3282,7 @@ export class StacklinkBotsClient {
3195
3282
  deleteCustomerData(botId, sessionId) { return this.client.request(`/v1/bots/${encodeURIComponent(botId)}/customer-data/delete`, { method: 'POST', body: { sessionId } }); }
3196
3283
  setState(botId, input) { return this.client.request(`/v1/bots/${encodeURIComponent(botId)}/state`, { method: 'POST', body: input }); }
3197
3284
  list() { return this.client.request('/v1/bots'); }
3198
- create(name) { return this.client.request('/v1/bots', { method: 'POST', body: { name } }); }
3285
+ create(name, identity) { return this.client.request('/v1/bots', { method: 'POST', body: { name, ...identity } }); }
3199
3286
  get(botId) { return this.client.request(`/v1/bots/${encodeURIComponent(botId)}`); }
3200
3287
  update(botId, revision, patch) { return this.client.request(`/v1/bots/${encodeURIComponent(botId)}`, { method: 'PATCH', body: { revision, patch } }); }
3201
3288
  publish(botId, revision, channels) { return this.client.request(`/v1/bots/${encodeURIComponent(botId)}/publish`, { method: 'POST', body: { revision, channels } }); }