@swarm-agent/sdk 0.1.47

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 (74) hide show
  1. package/APPLICATIONS.md +133 -0
  2. package/HEADLESS_UI.md +97 -0
  3. package/LICENSE +201 -0
  4. package/README.md +473 -0
  5. package/dist/app-results.d.ts +24 -0
  6. package/dist/app-results.js +167 -0
  7. package/dist/apps.d.ts +82 -0
  8. package/dist/apps.js +89 -0
  9. package/dist/auth.d.ts +45 -0
  10. package/dist/auth.js +89 -0
  11. package/dist/automations.d.ts +74 -0
  12. package/dist/automations.js +159 -0
  13. package/dist/client.d.ts +61 -0
  14. package/dist/client.js +103 -0
  15. package/dist/deliverables.d.ts +42 -0
  16. package/dist/deliverables.js +83 -0
  17. package/dist/deploy/dockerfile.d.ts +14 -0
  18. package/dist/deploy/dockerfile.js +14 -0
  19. package/dist/deploy/index.d.ts +67 -0
  20. package/dist/deploy/index.js +226 -0
  21. package/dist/deploy/manifest.d.ts +17 -0
  22. package/dist/deploy/manifest.js +220 -0
  23. package/dist/deploy/providers/gcp-cloud-run.d.ts +9 -0
  24. package/dist/deploy/providers/gcp-cloud-run.js +12 -0
  25. package/dist/deploy/providers/gcp-compute.d.ts +9 -0
  26. package/dist/deploy/providers/gcp-compute.js +12 -0
  27. package/dist/deploy/types.d.ts +211 -0
  28. package/dist/deploy/types.js +4 -0
  29. package/dist/deploy/worker-cloud-deployer.d.ts +33 -0
  30. package/dist/deploy/worker-cloud-deployer.js +14 -0
  31. package/dist/errors.d.ts +36 -0
  32. package/dist/errors.js +68 -0
  33. package/dist/index.d.ts +23 -0
  34. package/dist/index.js +20 -0
  35. package/dist/notifications.d.ts +28 -0
  36. package/dist/notifications.js +65 -0
  37. package/dist/projects.d.ts +147 -0
  38. package/dist/projects.js +513 -0
  39. package/dist/provider-auth.d.ts +160 -0
  40. package/dist/provider-auth.js +54 -0
  41. package/dist/realtime.d.ts +240 -0
  42. package/dist/realtime.js +312 -0
  43. package/dist/sessions.d.ts +60 -0
  44. package/dist/sessions.js +194 -0
  45. package/dist/settings.d.ts +85 -0
  46. package/dist/settings.js +26 -0
  47. package/dist/storage/adapters/memory.d.ts +13 -0
  48. package/dist/storage/adapters/memory.js +35 -0
  49. package/dist/storage/adapters/s3.d.ts +31 -0
  50. package/dist/storage/adapters/s3.js +171 -0
  51. package/dist/storage/client.d.ts +174 -0
  52. package/dist/storage/client.js +121 -0
  53. package/dist/storage/hub.d.ts +30 -0
  54. package/dist/storage/hub.js +372 -0
  55. package/dist/storage/index.d.ts +6 -0
  56. package/dist/storage/index.js +6 -0
  57. package/dist/storage/runner.d.ts +48 -0
  58. package/dist/storage/runner.js +233 -0
  59. package/dist/storage/types.d.ts +198 -0
  60. package/dist/storage/types.js +1 -0
  61. package/dist/system.d.ts +14 -0
  62. package/dist/system.js +52 -0
  63. package/dist/transport.d.ts +17 -0
  64. package/dist/transport.js +243 -0
  65. package/dist/types.d.ts +1137 -0
  66. package/dist/types.js +1 -0
  67. package/dist/usage.d.ts +106 -0
  68. package/dist/usage.js +82 -0
  69. package/dist/workers.d.ts +146 -0
  70. package/dist/workers.js +822 -0
  71. package/dist/workspaces.d.ts +81 -0
  72. package/dist/workspaces.js +58 -0
  73. package/examples/headless-session.ts +85 -0
  74. package/package.json +56 -0
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,106 @@
1
+ import type { SwarmTransport } from './transport.js';
2
+ export interface UsageScope {
3
+ kind: 'task' | 'worker' | 'worker_run';
4
+ id: string;
5
+ /** Project identity for tasks; worker identity for worker runs. */
6
+ project_id?: string;
7
+ }
8
+ export interface UsageScopeTotal extends UsageScope {
9
+ total_tokens: number;
10
+ input_tokens: number;
11
+ output_tokens: number;
12
+ cache_read_tokens: number;
13
+ cache_write_tokens: number;
14
+ thinking_tokens: number;
15
+ media_cost_usd: number;
16
+ media_receipts: number;
17
+ /** Only observed receipts; this is not proof of complete historical coverage. */
18
+ coverage: 'observed_receipts_only' | 'repaired_receipts_incomplete' | 'no_records' | '';
19
+ catalog_cost_usd: number;
20
+ provider_cost_usd: number;
21
+ provider_estimate_cost_usd: number;
22
+ nominal_subscription_cost_usd: number;
23
+ unknown_receipts: number;
24
+ free_receipts: number;
25
+ subscription_receipts: number;
26
+ receipt_count: number;
27
+ history_complete: boolean;
28
+ revision: number;
29
+ }
30
+ export interface UsageScopeRepairResult {
31
+ scanned: number;
32
+ repaired: number;
33
+ unresolved: number;
34
+ next_cursor?: string;
35
+ history_complete: boolean;
36
+ }
37
+ export declare class SwarmUsageNamespace {
38
+ private readonly transport;
39
+ constructor(transport: SwarmTransport);
40
+ workerBudget(workerId: string): Promise<WorkerBudgetStatus>;
41
+ /** User-only revision-guarded policy. Zero unsets a cap, never usage. In-flight
42
+ * provider work may overshoot; this is not an invoice-hard spending guarantee. */
43
+ setWorkerBudget(workerId: string, policy: WorkerBudgetUpdate): Promise<WorkerBudgetPolicy>;
44
+ private requestWorkerBudget;
45
+ /** Explicit bounded maintenance; no account charges are replayed. A finished
46
+ * cursor does not certify unavailable historic lineage or receipt indexes. */
47
+ repair(cursor?: string, limit?: number): Promise<UsageScopeRepairResult>;
48
+ /** Indexed cumulative receipt projection, not current context occupancy.
49
+ * recorded=false means no projection, not proof of free/zero historical usage.
50
+ * Optional date is one indexed UTC day; omitted date is lifetime observed usage.
51
+ * Refresh affected scopes from durable usage.scope.updated events, not polling.
52
+ */
53
+ scope(scope: UsageScope, date?: string): Promise<{
54
+ usage: UsageScopeTotal;
55
+ recorded: boolean;
56
+ }>;
57
+ }
58
+ /** Durable realtime event payload. Hydrate affected cards with scope(); no
59
+ * session subscription or recurring refresh is needed for scope invalidations. */
60
+ export interface UsageScopeUpdatedPayload {
61
+ scope_totals: UsageScopeTotal[];
62
+ }
63
+ export interface WorkerBudgetUpdate {
64
+ expected_revision: number;
65
+ daily_cost_limit_usd: number;
66
+ daily_tokens_limit: number;
67
+ }
68
+ export interface WorkerBudgetPolicy {
69
+ account_scope_id: string;
70
+ worker_id: string;
71
+ revision: number;
72
+ daily_cost_limit_usd: number;
73
+ daily_tokens_limit: number;
74
+ updated_at: number;
75
+ }
76
+ /** Indexed observed receipts, never an invoice-hard guarantee. Null remaining is unset. */
77
+ export interface WorkerBudgetStatus extends WorkerBudgetPolicy {
78
+ date: string;
79
+ usage: UsageScopeTotal;
80
+ remaining_cost_usd: number | null;
81
+ remaining_tokens: number | null;
82
+ blocked: boolean;
83
+ blocked_reason?: string;
84
+ inflight: boolean;
85
+ account_policy: {
86
+ account_scope_id: string;
87
+ enabled: boolean;
88
+ daily_cost_limit_usd: number;
89
+ daily_tokens_limit?: number;
90
+ updated_at: number;
91
+ };
92
+ account_usage: {
93
+ account_scope_id: string;
94
+ date: string;
95
+ total_cost_usd: number;
96
+ total_tokens: number;
97
+ unknown_receipts?: number;
98
+ pricing_coverage_version?: number;
99
+ pricing_coverage_incomplete?: boolean;
100
+ };
101
+ account_remaining_cost_usd: number | null;
102
+ account_remaining_tokens: number | null;
103
+ account_inflight: boolean;
104
+ account_coverage: 'no_records' | 'observed_receipts_only' | 'legacy_pricing_incomplete';
105
+ limitations: string;
106
+ }
package/dist/usage.js ADDED
@@ -0,0 +1,82 @@
1
+ import { SwarmValidationError } from './errors.js';
2
+ export class SwarmUsageNamespace {
3
+ transport;
4
+ constructor(transport) {
5
+ this.transport = transport;
6
+ }
7
+ async workerBudget(workerId) {
8
+ const status = await this.requestWorkerBudget(workerId);
9
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(status.date) || !status.usage ||
10
+ typeof status.blocked !== 'boolean' || typeof status.inflight !== 'boolean' ||
11
+ !status.account_policy || !status.account_usage || typeof status.account_inflight !== 'boolean' ||
12
+ typeof status.limitations !== 'string' || !['no_records', 'observed_receipts_only', 'legacy_pricing_incomplete'].includes(status.account_coverage) ||
13
+ ![status.remaining_cost_usd, status.remaining_tokens, status.account_remaining_cost_usd, status.account_remaining_tokens]
14
+ .every(value => value === null || (typeof value === 'number' && Number.isFinite(value) && value >= 0))) {
15
+ throw new SwarmValidationError('Malformed worker budget status');
16
+ }
17
+ return status;
18
+ }
19
+ /** User-only revision-guarded policy. Zero unsets a cap, never usage. In-flight
20
+ * provider work may overshoot; this is not an invoice-hard spending guarantee. */
21
+ async setWorkerBudget(workerId, policy) {
22
+ if (!policy || !Number.isSafeInteger(policy.expected_revision) || policy.expected_revision < 0 ||
23
+ !Number.isFinite(policy.daily_cost_limit_usd) || policy.daily_cost_limit_usd < 0 ||
24
+ !Number.isSafeInteger(policy.daily_tokens_limit) || policy.daily_tokens_limit < 0) {
25
+ throw new SwarmValidationError('Valid worker budget policy is required');
26
+ }
27
+ return this.requestWorkerBudget(workerId, policy);
28
+ }
29
+ async requestWorkerBudget(workerId, policy) {
30
+ if (typeof workerId !== 'string' || !/^[a-zA-Z0-9_.-]{3,128}$/.test(workerId)) {
31
+ throw new SwarmValidationError('Valid worker identity is required');
32
+ }
33
+ const result = await this.transport.request(`/v3/usage/worker-budget?${new URLSearchParams({ worker_id: workerId })}`, policy ? { method: 'PUT', body: policy } : { method: 'GET' });
34
+ if (!result.data || result.data.worker_id !== workerId || !Number.isSafeInteger(result.data.revision)) {
35
+ throw new SwarmValidationError('Malformed worker budget response');
36
+ }
37
+ return result.data;
38
+ }
39
+ /** Explicit bounded maintenance; no account charges are replayed. A finished
40
+ * cursor does not certify unavailable historic lineage or receipt indexes. */
41
+ async repair(cursor = '', limit = 100) {
42
+ if (typeof cursor !== 'string' || cursor.length > 3072 || !Number.isInteger(limit) || limit < 1 || limit > 100) {
43
+ throw new SwarmValidationError('Valid bounded usage repair request is required');
44
+ }
45
+ const result = await this.transport.request('/v3/usage/scopes/repair', {
46
+ method: 'POST', body: { cursor, limit },
47
+ });
48
+ if (!result.data || typeof result.data.history_complete !== 'boolean') {
49
+ throw new SwarmValidationError('Malformed usage repair response');
50
+ }
51
+ return result.data;
52
+ }
53
+ /** Indexed cumulative receipt projection, not current context occupancy.
54
+ * recorded=false means no projection, not proof of free/zero historical usage.
55
+ * Optional date is one indexed UTC day; omitted date is lifetime observed usage.
56
+ * Refresh affected scopes from durable usage.scope.updated events, not polling.
57
+ */
58
+ async scope(scope, date) {
59
+ if (!scope || !['task', 'worker', 'worker_run'].includes(scope.kind) ||
60
+ typeof scope.id !== 'string' || !scope.id.trim() || scope.id.length > 256 ||
61
+ (scope.kind !== 'worker' && !scope.project_id?.trim()) ||
62
+ (scope.kind === 'worker' && scope.project_id) ||
63
+ (scope.project_id !== undefined && scope.project_id.length > 256)) {
64
+ throw new SwarmValidationError('Valid usage scope identity is required');
65
+ }
66
+ if (date !== undefined && (!/^\d{4}-\d{2}-\d{2}$/.test(date) ||
67
+ !Number.isFinite(Date.parse(`${date}T00:00:00Z`)) ||
68
+ new Date(`${date}T00:00:00Z`).toISOString().slice(0, 10) !== date)) {
69
+ throw new SwarmValidationError('Valid UTC usage date is required');
70
+ }
71
+ const query = new URLSearchParams({ kind: scope.kind, id: scope.id });
72
+ if (scope.project_id)
73
+ query.set('project_id', scope.project_id);
74
+ if (date)
75
+ query.set('date', date);
76
+ const result = await this.transport.request(`/v3/usage/scope?${query}`, { method: 'GET' });
77
+ if (!result.data?.usage || typeof result.data.recorded !== 'boolean') {
78
+ throw new SwarmValidationError('Malformed usage scope response');
79
+ }
80
+ return result.data;
81
+ }
82
+ }
@@ -0,0 +1,146 @@
1
+ import type { SwarmTransport } from './transport.js';
2
+ import type { WorkerRecord, WorkerRevisionRecord, WorkerRunRecord, PortableWorkerDefinition, CreateWorkerParams, UpdateWorkerParams, ListWorkersParams, ListWorkersResult, AttachWorkerAutomationParams, UpdateWorkerAutomationParams, RemoveWorkerAutomationParams, WorkerValidateResult, WorkerExportResult, ImportWorkerOptions, ActivateWorkerParams, PauseWorkerParams, ResumeWorkerParams, ArchiveWorkerParams, DeleteWorkerParams, SetWorkerAutomationEnabledParams, DirectWorkerRequestParams, TestWorkerRunParams, TriggerWorkerParams, MintWorkerTriggerTokenParams, MintWorkerTriggerTokenResult, ListWorkerRunsParams, ListWorkerRunsResult, GetWorkerRunParams, CancelWorkerRunParams } from './types.js';
3
+ /**
4
+ * SwarmWorkersNamespace manages durable, account-owned workers, their revisions,
5
+ * attached automations, and portable import/export definitions over canonical /v3/workers APIs.
6
+ *
7
+ * Distinct from legacy SwarmAutomationsNamespace which targets /v3/automations/v2.
8
+ */
9
+ export declare class SwarmWorkersNamespace {
10
+ private transport;
11
+ constructor(transport: SwarmTransport);
12
+ /**
13
+ * Creates a new durable worker in idle state.
14
+ * Requires nonblank name and idempotency_key; instructions may be empty.
15
+ * Server assigns stable identity and initial revision 1.
16
+ */
17
+ create(params: CreateWorkerParams): Promise<WorkerRecord>;
18
+ /**
19
+ * Retrieves a durable worker by its server ID or attached automation ID.
20
+ */
21
+ get(id: string): Promise<WorkerRecord | null>;
22
+ /**
23
+ * Lists durable workers with pagination, lifecycle filters, and cursor support.
24
+ */
25
+ list(params?: ListWorkersParams): Promise<ListWorkersResult>;
26
+ /**
27
+ * Updates a worker's definition with an explicit expected revision for optimistic concurrency.
28
+ * Body carries expected_revision only (no query params, no local_bindings).
29
+ */
30
+ update(id: string, expectedRevision: number, params: UpdateWorkerParams): Promise<WorkerRecord>;
31
+ /**
32
+ * Validates a portable worker definition document without persisting it.
33
+ * Sends raw PortableWorkerDefinition body and expects { valid: true, worker: doc }.
34
+ */
35
+ validate(definition: PortableWorkerDefinition | string): Promise<WorkerValidateResult>;
36
+ /**
37
+ * Exports a complete portable worker definition.
38
+ * Returns { worker: doc }.
39
+ */
40
+ export(id: string): Promise<WorkerExportResult>;
41
+ /**
42
+ * Imports a portable worker definition.
43
+ * Sends raw document body.
44
+ * - If mode is 'new' (default when targetWorkerId omitted): requires idempotencyKey option, queries ?mode=new&idempotency_key=...
45
+ * - If mode is 'update' (or targetWorkerId provided): requires targetWorkerId and expectedRevision, queries ?mode=update&worker_id=...&expected_revision=...
46
+ */
47
+ import(definition: PortableWorkerDefinition | string, options?: ImportWorkerOptions): Promise<WorkerRecord>;
48
+ /**
49
+ * Attaches an automation definition to the worker.
50
+ * Body carries { expected_worker_revision, automation }, no query param.
51
+ */
52
+ attachAutomation(params: AttachWorkerAutomationParams): Promise<WorkerRecord>;
53
+ /**
54
+ * Updates an existing attached automation definition on the worker.
55
+ * Body carries { expected_worker_revision, automation }, no query param.
56
+ */
57
+ updateAutomation(params: UpdateWorkerAutomationParams): Promise<WorkerRecord>;
58
+ /**
59
+ * Detaches/removes an automation definition from the worker.
60
+ */
61
+ removeAutomation(params: RemoveWorkerAutomationParams): Promise<WorkerRecord>;
62
+ /**
63
+ * Activates a stored worker with approved local workspace bindings.
64
+ * Transitions worker from idle/paused to active state.
65
+ */
66
+ activate(params: ActivateWorkerParams): Promise<WorkerRecord>;
67
+ /**
68
+ * Local deployment alias for activate: validates and activates with approved bindings.
69
+ */
70
+ deploy(params: ActivateWorkerParams): Promise<WorkerRecord>;
71
+ /**
72
+ * Pauses an active worker, closing admission and invalidating queued work.
73
+ */
74
+ pause(params: PauseWorkerParams): Promise<WorkerRecord>;
75
+ /**
76
+ * Resumes a paused worker without replaying cancelled work.
77
+ */
78
+ resume(params: ResumeWorkerParams): Promise<WorkerRecord>;
79
+ /**
80
+ * Archives a worker, stopping future work and disabling automations.
81
+ * Rejects if there are active running executions.
82
+ */
83
+ archive(params: ArchiveWorkerParams): Promise<WorkerRecord>;
84
+ /**
85
+ * Deletes a worker with safe stop barrier enforcement (tombstone).
86
+ * Rejects if there are active running executions.
87
+ */
88
+ delete(params: DeleteWorkerParams): Promise<{
89
+ ok: boolean;
90
+ deleted: boolean;
91
+ }>;
92
+ /**
93
+ * Enables a specific attached automation on the worker.
94
+ */
95
+ enableAutomation(params: SetWorkerAutomationEnabledParams): Promise<WorkerRecord>;
96
+ /**
97
+ * Disables a specific attached automation on the worker without stopping other jobs.
98
+ */
99
+ disableAutomation(params: SetWorkerAutomationEnabledParams): Promise<WorkerRecord>;
100
+ /**
101
+ * Dispatches a direct execution request to the worker without creating a persistent automation.
102
+ */
103
+ directRequest(params: DirectWorkerRequestParams): Promise<WorkerRunRecord>;
104
+ /**
105
+ * Dispatches an explicitly labelled test run. Does not enable schedules.
106
+ */
107
+ testRun(params: TestWorkerRunParams): Promise<WorkerRunRecord>;
108
+ /**
109
+ * Dispatches an authenticated external trigger to the worker or specific automation.
110
+ */
111
+ trigger(params: TriggerWorkerParams): Promise<WorkerRunRecord>;
112
+ /**
113
+ * Mints an authenticated scoped trigger token for this worker.
114
+ */
115
+ mintTriggerToken(params: MintWorkerTriggerTokenParams): Promise<MintWorkerTriggerTokenResult>;
116
+ /**
117
+ * Lists historical and active execution runs for a worker with pagination.
118
+ */
119
+ listRuns(params: ListWorkerRunsParams): Promise<ListWorkerRunsResult>;
120
+ /**
121
+ * Retrieves a single worker execution run by ID.
122
+ */
123
+ getRun(params: GetWorkerRunParams): Promise<WorkerRunRecord | null>;
124
+ /**
125
+ * Cancels an active or admitted execution run.
126
+ */
127
+ cancelRun(params: CancelWorkerRunParams): Promise<WorkerRunRecord>;
128
+ /**
129
+ * Retrieves revision history snapshots for a worker.
130
+ */
131
+ getHistory(params: {
132
+ worker_id: string;
133
+ limit?: number;
134
+ cursor?: string;
135
+ }): Promise<{
136
+ history: WorkerRevisionRecord[];
137
+ next_cursor?: string;
138
+ }>;
139
+ /**
140
+ * Retrieves a specific pinned revision snapshot of a worker.
141
+ */
142
+ getRevision(params: {
143
+ worker_id: string;
144
+ revision: number;
145
+ }): Promise<WorkerRevisionRecord | null>;
146
+ }