@sogni-ai/sogni-creative-agent-skill 3.18.0 โ†’ 3.19.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,6 +1,6 @@
1
1
  {
2
2
  "name": "sogni-creative-agent",
3
- "version": "3.18.0",
3
+ "version": "3.19.0",
4
4
  "description": "Sogni Creative Agent: image, video, and music generation via Sogni AI's decentralized GPU network. Supports personas, persistent memories, style transfer, and multi-step creative workflows.",
5
5
  "author": {
6
6
  "name": "Sogni AI",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sogni-creative-agent",
3
- "version": "3.18.0",
3
+ "version": "3.19.0",
4
4
  "description": "Create images, generative video, music, and polished image-folder loops with Sogni AI.",
5
5
  "author": {
6
6
  "name": "Sogni AI",
package/CHANGELOG.md CHANGED
@@ -1,3 +1,17 @@
1
+ # [3.19.0](https://github.com/Sogni-AI/sogni-creative-agent-skill/compare/v3.18.1...v3.19.0) (2026-07-28)
2
+
3
+
4
+ ### Features
5
+
6
+ * **cli:** lease per-process app IDs from a persistent slot pool ([#26](https://github.com/Sogni-AI/sogni-creative-agent-skill/issues/26)) ([ef0ae8b](https://github.com/Sogni-AI/sogni-creative-agent-skill/commit/ef0ae8b973e65f88a78b775fb1b791daca719d42))
7
+
8
+ # [3.18.1](https://github.com/Sogni-AI/sogni-creative-agent-skill/compare/v3.18.0...v3.18.1) (2026-07-28)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * **cli:** persist one recognizable `sogni-agent-<uuid>` application ID across SDK sessions to prevent repeated CLI runs from exhausting the per-address app-ID allowance ([#25](https://github.com/Sogni-AI/sogni-creative-agent-skill/issues/25))
14
+
1
15
  # [3.18.0](https://github.com/Sogni-AI/sogni-creative-agent-skill/compare/v3.17.2...v3.18.0) (2026-07-27)
2
16
 
3
17
 
package/README.md CHANGED
@@ -341,12 +341,18 @@ You can also skip the file and export `SOGNI_API_KEY` in your environment.
341
341
 
342
342
  ### Filesystem path overrides
343
343
 
344
- Defaults live under `~/.config/sogni/` for credentials, last-render metadata, personas, memories, and personality. Override individual paths with:
344
+ Defaults live under `~/.config/sogni/` for credentials, last-render metadata, personas, memories, and personality.
345
+
346
+ **Running several agents at once** (Claude Code, Codex, OpenCode, hermes, ...) works out of the box: each process leases its own stable app ID from a persistent slot pool in `~/.config/sogni/app-ids/`, so concurrent runs never fight over one socket identity (SWITCH_CONNECTION 4015) and routine runs never mint new IDs against the per-address daily allowance (error 4061). Leases are released on exit and reclaimed automatically if a process dies. Long-lived daemons should pin their own `SOGNI_APP_ID` to stay out of the shared pool, and each harness can set its own `SOGNI_LAST_RENDER_PATH` so `--last` stays per-tool. Override individual paths with:
345
347
 
346
348
  | Variable | Purpose |
347
349
  |----------|---------|
348
350
  | `SOGNI_CREDENTIALS_PATH` | Custom credentials file |
349
- | `SOGNI_LAST_RENDER_PATH` | Where last-render state is persisted |
351
+ | `SOGNI_APP_ID` | Pinned app ID (ephemeral/container homes and long-lived daemons; skips the pool) |
352
+ | `SOGNI_APP_ID_PATH` | Legacy single app-ID file mode for callers that manage their own concurrency |
353
+ | `SOGNI_APP_ID_POOL_DIR` | Persistent app-ID slot pool for concurrent agents (default: `~/.config/sogni/app-ids/`) |
354
+ | `SOGNI_APP_ID_POOL_MAX` | Maximum concurrent app-ID slots (default: 32) |
355
+ | `SOGNI_LAST_RENDER_PATH` | Where last-render state is persisted; give each agent harness its own file so `--last` never reads another tool's render |
350
356
  | `SOGNI_MODEL_CATALOG_URL` | Model catalog API base URL (default: `https://api.sogni.ai/v1/model-catalog`) |
351
357
  | `SOGNI_MODEL_CATALOG_CACHE_PATH` | Base path for the five-minute model catalog caches and ETags |
352
358
  | `SOGNI_MEDIA_INBOUND_DIR` | Directory used by `--list-media` |
package/SKILL.md CHANGED
@@ -2,7 +2,7 @@
2
2
  name: sogni-creative-agent-skill
3
3
  description: "Sogni Creative Agent Skill: agent skill and CLI for image, video, and music generation using Sogni AI's decentralized GPU network. Supports one-click image-folder loop reels, personas (named people with saved reference photos and voice clips), persistent memories, custom personality, style transfer, angle synthesis, Seedance/HappyHorse/LTX/WAN video, music/lyrics, hosted chat, durable workflows, replay records, and multi-step creative workflows. Ask the agent to \"draw\", \"generate\", \"create an image\", \"make a video/animate\", \"turn this image folder into a loop\", \"make music\", \"apply a style\", or \"generate me as a superhero\"."
4
4
  metadata:
5
- version: "3.18.0"
5
+ version: "3.19.0"
6
6
  homepage: https://sogni.ai
7
7
  openclaw:
8
8
  emoji: "๐ŸŽจ"
@@ -94,6 +94,7 @@ sogni-agent -o /tmp/cat.png "a cat wearing a hat" # โœ— avoid โ€” user can't
94
94
  ## Filesystem Paths and Overrides
95
95
 
96
96
  - API key credentials file (read): `~/.config/sogni/credentials` (`SOGNI_CREDENTIALS_PATH`)
97
+ - Reusable app-ID slot pool (read/write): `~/.config/sogni/app-ids/slot-<n>` plus `.lease` files; new IDs use `sogni-agent-<uuid>` (`SOGNI_APP_ID_POOL_DIR`/`SOGNI_APP_ID_POOL_MAX`). Concurrent agent processes lease distinct slots automatically; the legacy single `~/.config/sogni/app-id` file migrates into slot-0 on first use. Set a stable `SOGNI_APP_ID` for ephemeral/container homes or long-lived daemons, or `SOGNI_APP_ID_PATH` for legacy single-file mode.
97
98
  - Last render metadata (read/write): `~/.config/sogni/last-render.json` (`SOGNI_LAST_RENDER_PATH`)
98
99
  - Model catalog: `https://api.sogni.ai/v1/model-catalog` (`SOGNI_MODEL_CATALOG_URL`)
99
100
  - Model catalog cache (read/write, 5-minute TTL with ETag revalidation for model parameters and discovery): `~/.config/sogni/model-catalog-cache.json` (`SOGNI_MODEL_CATALOG_CACHE_PATH`)
@@ -335,6 +336,8 @@ Eligible Sogni-hosted renders use Unlimited coverage when active; otherwise rend
335
336
 
336
337
  - **Anything broken?** Run `sogni-agent doctor` first โ€” it checks Node, credentials (and file permissions), config-dir writability, ffmpeg, live auth, and version freshness, with a fix in every failure detail.
337
338
  - **Auth errors:** check `SOGNI_API_KEY` or `~/.config/sogni/credentials` (key from https://dashboard.sogni.ai, account menu).
339
+ - **Error 4061 / too many app IDs:** the CLI leases stable IDs from the persistent pool in `~/.config/sogni/app-ids/`. Do not delete that directory between runs. For ephemeral/container homes, set the same `SOGNI_APP_ID` on every session. App IDs already registered today remain counted until 00:00 UTC, so an existing block may require waiting for that reset once after upgrading.
340
+ - **Kicked mid-render / SWITCH_CONNECTION 4015:** two processes shared one app ID. The slot pool prevents this for concurrent CLI runs; if a long-lived daemon also uses this account, give it its own pinned `SOGNI_APP_ID`.
338
341
  - **Video size errors:** sizes are model-specific (WAN รท16 min 480 max 1536; LTX รท64, long side โ‰ค2048). The CLI auto-adjusts for local refs; `--strict-size` makes it fail with a suggested size instead. Details in [`references/models.md`](./references/models.md).
339
342
  - **Timeouts:** try a faster model or raise `-t`.
340
343
  - **No workers:** check https://sogni.ai for network status.
@@ -2,7 +2,7 @@
2
2
  "manifest_version": "0.3",
3
3
  "name": "sogni-creative-agent",
4
4
  "display_name": "Sogni Creative Agent",
5
- "version": "3.18.0",
5
+ "version": "3.19.0",
6
6
  "description": "Generate images, video, and music on Sogni AI's decentralized GPU network โ€” with personas, memories, and safe video editing tools.",
7
7
  "author": { "name": "Sogni AI", "url": "https://sogni.ai" },
8
8
  "homepage": "https://sogni.ai",
package/llm.txt CHANGED
@@ -74,6 +74,13 @@ chmod 600 ~/.config/sogni/credentials
74
74
  You can also export `SOGNI_API_KEY` instead of writing the file. Confirm with
75
75
  `sogni-agent doctor`.
76
76
 
77
+ The CLI leases a stable app ID per process from a persistent slot pool in
78
+ `~/.config/sogni/app-ids/`, so concurrent agents (Claude Code, Codex,
79
+ OpenCode, hermes, ...) never share one socket identity and routine runs never
80
+ mint new IDs. Preserve that directory between sessions. In ephemeral
81
+ containers, set one stable `SOGNI_APP_ID` value; rotating IDs on each run can
82
+ trigger Sogni error 4061 (allowance resets at 00:00 UTC).
83
+
77
84
  ## Hosted API modes (require SOGNI_API_KEY)
78
85
 
79
86
  - `sogni-agent --api-chat "prompt"` โ€” `/v1/chat/completions` with hosted
@@ -2,7 +2,7 @@
2
2
  "id": "sogni-creative-agent-skill",
3
3
  "name": "Sogni Creative Agent Skill โ€” Image, Video & Music Generation",
4
4
  "description": "Agent skill and CLI for Sogni AI image, video, and music generation.",
5
- "version": "3.18.0",
5
+ "version": "3.19.0",
6
6
  "skills": [
7
7
  "."
8
8
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sogni-ai/sogni-creative-agent-skill",
3
- "version": "3.18.0",
3
+ "version": "3.19.0",
4
4
  "description": "Sogni Creative Agent Skill: agent skill and CLI for Sogni AI image, video, and music generation.",
5
5
  "type": "module",
6
6
  "main": "sogni-agent.mjs",
@@ -79,6 +79,7 @@
79
79
  "openclaw.plugin.json",
80
80
  "env.mjs",
81
81
  "ssrf-guard.mjs",
82
+ "sogni-app-id.mjs",
82
83
  "sogni-hosted-client.mjs",
83
84
  "update-check.mjs",
84
85
  "node-version-check.mjs",
package/sogni-agent.mjs CHANGED
@@ -16,6 +16,7 @@ import { join, dirname, basename, extname, sep, resolve } from 'path';
16
16
  import { homedir, tmpdir } from 'os';
17
17
  import sharp from 'sharp';
18
18
  import { getEnv, hasEnv } from './env.mjs';
19
+ import { getOrCreateSogniAppId } from './sogni-app-id.mjs';
19
20
  import { PACKAGE_VERSION } from './version.mjs';
20
21
  import { assertSafeUrl, fetchSafeUrl } from './ssrf-guard.mjs';
21
22
  import {
@@ -120,6 +121,9 @@ const KNOWN_MODEL_CATALOG_TAGS = new Set([
120
121
  // covered job that cannot bill. Codes are the source of truth in
121
122
  // sogni-socket/constants/errorCodes.js (4078-4081).
122
123
  const SUBSCRIPTION_BILLING_ERROR_CODES = new Set(['4078', '4079', '4080', '4081']);
124
+ const APP_ID_LIMIT_ERROR_CODE = '4061';
125
+ const APP_ID_LIMIT_HINT =
126
+ 'This CLI now persists and reuses one installation app ID. Keep ~/.config/sogni/app-id between sessions; for ephemeral/container homes, set one stable SOGNI_APP_ID or persist SOGNI_APP_ID_PATH. App IDs already registered from this address remain counted until 00:00 UTC, so wait for the next UTC reset once if the address is already blocked.';
123
127
 
124
128
  function subscriptionBillingFallback(code) {
125
129
  if (code === undefined || code === null) return null;
@@ -191,6 +195,24 @@ function subscriptionBillingCodeFromError(error) {
191
195
  ?? record.payload?.error_code;
192
196
  }
193
197
 
198
+ function isAppIdLimitError(error) {
199
+ if (!error) return false;
200
+ const code = error.code
201
+ ?? error.errorCode
202
+ ?? error.error_code
203
+ ?? error.payload?.errorCode
204
+ ?? error.payload?.error_code;
205
+ if (String(code) === APP_ID_LIMIT_ERROR_CODE) return true;
206
+ const message = `${error.message || ''} ${error.reason || ''} ${error.payload?.message || ''}`.toLowerCase();
207
+ return message.includes('too many app-ids') || message.includes('too many app ids');
208
+ }
209
+
210
+ function enrichAppIdLimitError(error) {
211
+ if (!isAppIdLimitError(error)) return;
212
+ error.code = APP_ID_LIMIT_ERROR_CODE;
213
+ if (!error.hint) error.hint = APP_ID_LIMIT_HINT;
214
+ }
215
+
194
216
  const require = createRequire(import.meta.url);
195
217
  const rootClientModule = process.env.SOGNI_AGENT_TEST_STATE_PATH
196
218
  ? await import('@sogni-ai/sogni-intelligence-client')
@@ -855,6 +877,7 @@ function reportFatalError(error) {
855
877
  if (getEnv('SOGNI_DEBUG') || getEnv('DEBUG')) {
856
878
  console.error(error?.stack || String(error));
857
879
  }
880
+ enrichAppIdLimitError(error);
858
881
  if (isInvalidApiKeyError(error)) {
859
882
  fatalCliError('Invalid Sogni API key.', {
860
883
  code: 'INVALID_API_KEY',
@@ -878,6 +901,7 @@ async function connectSogniClient(client) {
878
901
  try {
879
902
  await client.connect();
880
903
  } catch (error) {
904
+ enrichAppIdLimitError(error);
881
905
  if (isInvalidApiKeyError(error) && !error.hint) {
882
906
  error.hint = INVALID_API_KEY_HINT;
883
907
  if (!error.code) error.code = 'INVALID_API_KEY';
@@ -4971,7 +4995,7 @@ async function dispatchWorkflowActionViaSdk(action, apiKey, params) {
4971
4995
  restEndpoint: restBase,
4972
4996
  socketEndpoint: process.env.SOGNI_SOCKET_ENDPOINT || undefined,
4973
4997
  appSource: SOGNI_APP_SOURCE,
4974
- appId: `sogni-skill-sdk-${process.pid}-${Date.now()}`,
4998
+ appId: getOrCreateSogniAppId(),
4975
4999
  },
4976
5000
  async (client) => {
4977
5001
  if (action === 'list') {
@@ -5049,7 +5073,7 @@ async function dispatchChatHostedViaSdk(apiKey, body) {
5049
5073
  restEndpoint: restBase,
5050
5074
  socketEndpoint: process.env.SOGNI_SOCKET_ENDPOINT || undefined,
5051
5075
  appSource: SOGNI_APP_SOURCE,
5052
- appId: `sogni-skill-sdk-${process.pid}-${Date.now()}`,
5076
+ appId: getOrCreateSogniAppId(),
5053
5077
  },
5054
5078
  async (client) => helpers.sdkChatHostedCreate(client, body),
5055
5079
  );
@@ -5092,7 +5116,7 @@ async function dispatchMediaReferenceUrlViaSdk({ ref, file, index, jobId, action
5092
5116
  restEndpoint: restBase,
5093
5117
  socketEndpoint: process.env.SOGNI_SOCKET_ENDPOINT || undefined,
5094
5118
  appSource: SOGNI_APP_SOURCE,
5095
- appId: `sogni-skill-sdk-${process.pid}-${Date.now()}`,
5119
+ appId: getOrCreateSogniAppId(),
5096
5120
  },
5097
5121
  async (client) => {
5098
5122
  const type = apiMediaReferenceUploadType(ref, index);
@@ -5880,7 +5904,7 @@ async function runApiChatDurable(log, { apiKey, body }) {
5880
5904
  restEndpoint: restBase,
5881
5905
  socketEndpoint: process.env.SOGNI_SOCKET_ENDPOINT || undefined,
5882
5906
  appSource: SOGNI_APP_SOURCE,
5883
- appId: `sogni-skill-sdk-${process.pid}-${Date.now()}`,
5907
+ appId: getOrCreateSogniAppId(),
5884
5908
  },
5885
5909
  async (client) => {
5886
5910
  const created = await helpers.sdkChatRunsCreate(client, runParams);
@@ -9413,6 +9437,7 @@ async function runDoctor() {
9413
9437
  try {
9414
9438
  doctorClient = new SogniClientWrapper({
9415
9439
  appSource: SOGNI_APP_SOURCE,
9440
+ appId: getOrCreateSogniAppId(),
9416
9441
  network: openclawConfig?.defaultNetwork || 'fast',
9417
9442
  autoConnect: false,
9418
9443
  apiKey: creds.SOGNI_API_KEY,
@@ -9954,6 +9979,7 @@ async function main() {
9954
9979
  log('Connecting to Sogni...');
9955
9980
  client = new SogniClientWrapper({
9956
9981
  appSource: SOGNI_APP_SOURCE,
9982
+ appId: getOrCreateSogniAppId(),
9957
9983
  network: openclawConfig?.defaultNetwork || 'fast',
9958
9984
  autoConnect: false,
9959
9985
  apiKey: creds.SOGNI_API_KEY,
@@ -10911,6 +10937,7 @@ async function main() {
10911
10937
  const creds = loadCredentials();
10912
10938
  const client2 = new SogniClientWrapper({
10913
10939
  appSource: SOGNI_APP_SOURCE,
10940
+ appId: getOrCreateSogniAppId(),
10914
10941
  network: openclawConfig?.defaultNetwork || 'fast',
10915
10942
  autoConnect: false,
10916
10943
  apiKey: creds.SOGNI_API_KEY,
@@ -11118,6 +11145,7 @@ async function main() {
11118
11145
  if (!error.hint) error.hint = INVALID_API_KEY_HINT;
11119
11146
  if (!error.code) error.code = 'INVALID_API_KEY';
11120
11147
  }
11148
+ enrichAppIdLimitError(error);
11121
11149
 
11122
11150
  exitCode = 1;
11123
11151
  const shouldJson = options.json || IS_OPENCLAW_INVOCATION;
@@ -0,0 +1,337 @@
1
+ /**
2
+ * Persistent Sogni application identity.
3
+ *
4
+ * Sogni limits how many distinct app IDs may connect from one address each
5
+ * UTC day. An app ID therefore represents an installation, not a process or
6
+ * request. Keep it outside credentials so rotating an API key does not rotate
7
+ * the installation identity.
8
+ *
9
+ * A single shared app ID is not enough once several agent harnesses (Claude
10
+ * Code, Codex, OpenCode, hermes, ...) drive this CLI concurrently: the socket
11
+ * server allows one live connection per app ID and answers a second claim
12
+ * with SWITCH_CONNECTION (4015), kicking the first process mid-render. The
13
+ * default mode is therefore a small pool of persistent per-slot app IDs under
14
+ * `~/.config/sogni/app-ids/`. Each process leases the lowest free slot for
15
+ * its lifetime (lease liveness = pid check), so concurrent processes get
16
+ * distinct stable IDs, the pool only grows to the actual peak concurrency,
17
+ * and no new ID is minted on routine runs.
18
+ */
19
+ import { randomUUID } from 'node:crypto';
20
+ import {
21
+ closeSync,
22
+ mkdirSync,
23
+ openSync,
24
+ readFileSync,
25
+ readdirSync,
26
+ unlinkSync,
27
+ writeFileSync,
28
+ } from 'node:fs';
29
+ import { homedir } from 'node:os';
30
+ import { basename, dirname, join } from 'node:path';
31
+ import { getEnv } from './env.mjs';
32
+
33
+ const DEFAULT_APP_ID_PATH = join(homedir(), '.config', 'sogni', 'app-id');
34
+ const DEFAULT_APP_ID_POOL_DIR = join(homedir(), '.config', 'sogni', 'app-ids');
35
+ const DEFAULT_APP_ID_POOL_MAX = 32;
36
+ const GENERATED_APP_ID_PREFIX = 'sogni-agent-';
37
+ const MAX_APP_ID_LENGTH = 256;
38
+ const APP_ID_CREATE_RETRIES = 20;
39
+ const APP_ID_CREATE_RETRY_MS = 5;
40
+
41
+ function expandHomePath(rawPath) {
42
+ if (rawPath === '~') return homedir();
43
+ if (rawPath?.startsWith('~/') || rawPath?.startsWith('~\\')) {
44
+ return join(homedir(), rawPath.slice(2));
45
+ }
46
+ return rawPath;
47
+ }
48
+
49
+ function validateAppId(value, source) {
50
+ const appId = typeof value === 'string' ? value.trim() : '';
51
+ if (!appId) {
52
+ const error = new Error(`${source} is empty.`);
53
+ error.code = 'INVALID_APP_ID';
54
+ error.hint = 'Set SOGNI_APP_ID to one stable non-empty identifier, or remove the empty app-id file so the CLI can recreate it.';
55
+ throw error;
56
+ }
57
+ if (appId.length > MAX_APP_ID_LENGTH || /[\x00-\x1f\x7f]/.test(appId)) {
58
+ const error = new Error(`${source} must be at most ${MAX_APP_ID_LENGTH} characters and contain no control characters.`);
59
+ error.code = 'INVALID_APP_ID';
60
+ error.hint = 'Set SOGNI_APP_ID to one stable UUID-style identifier.';
61
+ throw error;
62
+ }
63
+ return appId;
64
+ }
65
+
66
+ function waitForConcurrentWriter() {
67
+ // Another process can observe the file in the tiny interval between its
68
+ // exclusive creation and first write. Atomics.wait gives that writer a few
69
+ // milliseconds without introducing an async API into client construction.
70
+ const signal = new Int32Array(new SharedArrayBuffer(4));
71
+ Atomics.wait(signal, 0, 0, APP_ID_CREATE_RETRY_MS);
72
+ }
73
+
74
+ function readPersistedAppId(appIdPath) {
75
+ return validateAppId(readFileSync(appIdPath, 'utf8'), `Sogni app-id file ${appIdPath}`);
76
+ }
77
+
78
+ function appIdPersistenceError(error, appIdPath) {
79
+ if (error?.code === 'INVALID_APP_ID' || error?.code === 'APP_ID_POOL_EXHAUSTED') return error;
80
+ const wrapped = new Error(`Could not persist the Sogni app ID at ${appIdPath}: ${error?.message || error}`);
81
+ wrapped.code = 'APP_ID_PERSISTENCE_FAILED';
82
+ wrapped.hint = 'Make that location writable, set SOGNI_APP_ID_PATH to a persistent writable file, or set one stable SOGNI_APP_ID value for every session.';
83
+ return wrapped;
84
+ }
85
+
86
+ /**
87
+ * Create-once/read-forever identity file. Concurrent first launches race on
88
+ * exclusive create; losers reuse the winner's value.
89
+ */
90
+ function getOrCreateAppIdFile(resolvedPath, generateUuid) {
91
+ try {
92
+ return readPersistedAppId(resolvedPath);
93
+ } catch (error) {
94
+ if (error?.code !== 'ENOENT') throw error;
95
+ }
96
+
97
+ mkdirSync(dirname(resolvedPath), { recursive: true, mode: 0o700 });
98
+ const candidate = validateAppId(
99
+ `${GENERATED_APP_ID_PREFIX}${generateUuid()}`,
100
+ 'Generated Sogni app ID',
101
+ );
102
+ let descriptor;
103
+ let createdFile = false;
104
+ try {
105
+ descriptor = openSync(resolvedPath, 'wx', 0o600);
106
+ createdFile = true;
107
+ writeFileSync(descriptor, `${candidate}\n`, 'utf8');
108
+ return candidate;
109
+ } catch (error) {
110
+ if (error?.code !== 'EEXIST') throw error;
111
+
112
+ // A concurrent first launch won the exclusive create. Reuse its value
113
+ // once the short write window closes.
114
+ let lastError = error;
115
+ for (let attempt = 0; attempt < APP_ID_CREATE_RETRIES; attempt += 1) {
116
+ try {
117
+ return readPersistedAppId(resolvedPath);
118
+ } catch (readError) {
119
+ lastError = readError;
120
+ if (attempt + 1 < APP_ID_CREATE_RETRIES) waitForConcurrentWriter();
121
+ }
122
+ }
123
+ throw lastError;
124
+ } finally {
125
+ if (descriptor !== undefined) closeSync(descriptor);
126
+ // Do not strand an empty/corrupt identity if this process created the
127
+ // file but could not finish writing it.
128
+ if (createdFile) {
129
+ try {
130
+ readPersistedAppId(resolvedPath);
131
+ } catch {
132
+ try { unlinkSync(resolvedPath); } catch { /* best effort */ }
133
+ }
134
+ }
135
+ }
136
+ }
137
+
138
+ function defaultIsPidAlive(pid) {
139
+ try {
140
+ process.kill(pid, 0);
141
+ return true;
142
+ } catch (error) {
143
+ // EPERM means the pid exists but belongs to another user; treat as alive.
144
+ return error?.code === 'EPERM';
145
+ }
146
+ }
147
+
148
+ function leaseIsStale(leasePath, { isPidAlive, ownPid }) {
149
+ let record;
150
+ try {
151
+ record = JSON.parse(readFileSync(leasePath, 'utf8'));
152
+ } catch (error) {
153
+ if (error?.code === 'ENOENT') return false; // released while we looked
154
+ return true; // unreadable/corrupt lease can never be released by its owner
155
+ }
156
+ const pid = record?.pid;
157
+ if (!Number.isInteger(pid) || pid <= 0) return true;
158
+ // A lease naming our own pid cannot be live: this process acquires at most
159
+ // one lease and caches it, so this is a leftover from a recycled pid.
160
+ if (pid === ownPid) return true;
161
+ return !isPidAlive(pid);
162
+ }
163
+
164
+ function tryCreateLease(leasePath, ownPid) {
165
+ let descriptor;
166
+ try {
167
+ descriptor = openSync(leasePath, 'wx', 0o600);
168
+ const record = {
169
+ pid: ownPid,
170
+ tool: basename(process.argv[1] || 'sogni-agent'),
171
+ acquiredAt: new Date().toISOString(),
172
+ };
173
+ writeFileSync(descriptor, `${JSON.stringify(record)}\n`, 'utf8');
174
+ return true;
175
+ } catch (error) {
176
+ if (error?.code === 'EEXIST') return false;
177
+ throw error;
178
+ } finally {
179
+ if (descriptor !== undefined) closeSync(descriptor);
180
+ }
181
+ }
182
+
183
+ /**
184
+ * One-time migration: the pre-pool single `app-id` file becomes slot-0 so an
185
+ * upgraded installation keeps its already-registered identity instead of
186
+ * burning a new one. The legacy file is removed so a stray old-CLI process
187
+ * cannot share (and steal) slot-0's connection.
188
+ */
189
+ function migrateLegacyAppId(poolDir, legacyAppIdPath) {
190
+ if (!legacyAppIdPath) return;
191
+ let legacyValue;
192
+ try {
193
+ legacyValue = readPersistedAppId(legacyAppIdPath);
194
+ } catch {
195
+ return; // absent or corrupt legacy identity: nothing worth migrating
196
+ }
197
+ let descriptor;
198
+ try {
199
+ descriptor = openSync(join(poolDir, 'slot-0'), 'wx', 0o600);
200
+ writeFileSync(descriptor, `${legacyValue}\n`, 'utf8');
201
+ } catch (error) {
202
+ if (error?.code !== 'EEXIST') throw error;
203
+ return; // pool already initialized; leave the legacy file alone
204
+ } finally {
205
+ if (descriptor !== undefined) closeSync(descriptor);
206
+ }
207
+ try { unlinkSync(legacyAppIdPath); } catch { /* best effort */ }
208
+ }
209
+
210
+ function parsePoolMax(rawValue) {
211
+ const parsed = Number.parseInt(rawValue ?? '', 10);
212
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_APP_ID_POOL_MAX;
213
+ }
214
+
215
+ let processLease = null;
216
+ let exitCleanupRegistered = false;
217
+
218
+ /** Release this process's pool lease (also used by tests to reset state). */
219
+ export function releaseSogniAppId() {
220
+ if (!processLease) return;
221
+ try { unlinkSync(processLease.leasePath); } catch { /* best effort */ }
222
+ processLease = null;
223
+ }
224
+
225
+ function registerExitCleanup() {
226
+ if (exitCleanupRegistered) return;
227
+ exitCleanupRegistered = true;
228
+ process.on('exit', releaseSogniAppId);
229
+ }
230
+
231
+ function acquireSlotLease({ poolDir, poolMax, generateUuid, isPidAlive, ownPid, legacyAppIdPath }) {
232
+ mkdirSync(poolDir, { recursive: true, mode: 0o700 });
233
+ migrateLegacyAppId(poolDir, legacyAppIdPath);
234
+ for (let slot = 0; slot < poolMax; slot += 1) {
235
+ const slotPath = join(poolDir, `slot-${slot}`);
236
+ const appId = getOrCreateAppIdFile(slotPath, generateUuid);
237
+ const leasePath = `${slotPath}.lease`;
238
+ if (tryCreateLease(leasePath, ownPid)) return { appId, leasePath };
239
+ if (leaseIsStale(leasePath, { isPidAlive, ownPid })) {
240
+ try { unlinkSync(leasePath); } catch { /* another reclaimer won */ }
241
+ if (tryCreateLease(leasePath, ownPid)) return { appId, leasePath };
242
+ }
243
+ }
244
+ const error = new Error(`All ${poolMax} Sogni app-ID slots in ${poolDir} are leased by live processes.`);
245
+ error.code = 'APP_ID_POOL_EXHAUSTED';
246
+ error.hint = 'Raise SOGNI_APP_ID_POOL_MAX, or give long-lived daemons their own stable SOGNI_APP_ID so they stay out of the shared pool.';
247
+ throw error;
248
+ }
249
+
250
+ /**
251
+ * Return the stable app ID for this process, creating identity state at most
252
+ * once per installation.
253
+ *
254
+ * Resolution order:
255
+ * 1. `SOGNI_APP_ID` โ€” explicit pinned value (ephemeral/container homes and
256
+ * long-lived daemons that must keep one identity). No files touched.
257
+ * 2. `SOGNI_APP_ID_PATH` โ€” legacy single-file mode for callers that manage
258
+ * their own concurrency; behaves exactly like pre-pool releases.
259
+ * 3. Default โ€” lease a slot from the persistent pool so concurrent agent
260
+ * processes each hold a distinct stable ID (`SOGNI_APP_ID_POOL_DIR`,
261
+ * `SOGNI_APP_ID_POOL_MAX`). The lease is released on process exit and
262
+ * reclaimed via pid-liveness if the process dies uncleanly.
263
+ */
264
+ export function getOrCreateSogniAppId({
265
+ appId = getEnv('SOGNI_APP_ID', { trim: true }),
266
+ appIdPath = getEnv('SOGNI_APP_ID_PATH', { trim: true }),
267
+ poolDir = getEnv('SOGNI_APP_ID_POOL_DIR', { trim: true }) || DEFAULT_APP_ID_POOL_DIR,
268
+ poolMax = parsePoolMax(getEnv('SOGNI_APP_ID_POOL_MAX', { trim: true })),
269
+ generateUuid = randomUUID,
270
+ isPidAlive = defaultIsPidAlive,
271
+ ownPid = process.pid,
272
+ legacyAppIdPath,
273
+ } = {}) {
274
+ if (appId) return validateAppId(appId, 'SOGNI_APP_ID');
275
+
276
+ if (appIdPath) {
277
+ const resolvedPath = expandHomePath(appIdPath);
278
+ try {
279
+ return getOrCreateAppIdFile(resolvedPath, generateUuid);
280
+ } catch (error) {
281
+ throw appIdPersistenceError(error, resolvedPath);
282
+ }
283
+ }
284
+
285
+ if (processLease) return processLease.appId;
286
+ const resolvedPoolDir = expandHomePath(poolDir);
287
+ if (legacyAppIdPath === undefined) {
288
+ // Only the real default pool inherits the real pre-pool identity file; a
289
+ // custom pool location must never consume (and delete) it as a side effect.
290
+ legacyAppIdPath = resolvedPoolDir === DEFAULT_APP_ID_POOL_DIR ? DEFAULT_APP_ID_PATH : null;
291
+ }
292
+ try {
293
+ processLease = acquireSlotLease({
294
+ poolDir: resolvedPoolDir,
295
+ poolMax,
296
+ generateUuid,
297
+ isPidAlive,
298
+ ownPid,
299
+ legacyAppIdPath,
300
+ });
301
+ } catch (error) {
302
+ throw appIdPersistenceError(error, resolvedPoolDir);
303
+ }
304
+ registerExitCleanup();
305
+ return processLease.appId;
306
+ }
307
+
308
+ /** Diagnostic view of the pool for doctor/debug output. */
309
+ export function describeSogniAppIdPool({
310
+ poolDir = getEnv('SOGNI_APP_ID_POOL_DIR', { trim: true }) || DEFAULT_APP_ID_POOL_DIR,
311
+ isPidAlive = defaultIsPidAlive,
312
+ } = {}) {
313
+ const resolvedPoolDir = expandHomePath(poolDir);
314
+ let names;
315
+ try {
316
+ names = readdirSync(resolvedPoolDir);
317
+ } catch {
318
+ return { poolDir: resolvedPoolDir, slots: [] };
319
+ }
320
+ const slots = names
321
+ .filter((name) => /^slot-\d+$/.test(name))
322
+ .sort((a, b) => Number(a.slice(5)) - Number(b.slice(5)))
323
+ .map((name) => {
324
+ const slotPath = join(resolvedPoolDir, name);
325
+ let appId = null;
326
+ try { appId = readPersistedAppId(slotPath); } catch { /* corrupt slot */ }
327
+ let lease = null;
328
+ try {
329
+ lease = JSON.parse(readFileSync(`${slotPath}.lease`, 'utf8'));
330
+ lease.live = Number.isInteger(lease?.pid) && lease.pid > 0 && isPidAlive(lease.pid);
331
+ } catch { /* no lease */ }
332
+ return { slot: name, appId, lease };
333
+ });
334
+ return { poolDir: resolvedPoolDir, slots };
335
+ }
336
+
337
+ export { DEFAULT_APP_ID_PATH, DEFAULT_APP_ID_POOL_DIR };
@@ -25,6 +25,7 @@
25
25
  */
26
26
  import { createRequire } from 'node:module';
27
27
  import { assertSafeUrl } from './ssrf-guard.mjs';
28
+ import { getOrCreateSogniAppId } from './sogni-app-id.mjs';
28
29
 
29
30
  const require = createRequire(import.meta.url);
30
31
  const { SogniClient } = require('@sogni-ai/sogni-intelligence-client');
@@ -75,7 +76,7 @@ export async function assertSafeSogniEndpoints({ restEndpoint, socketEndpoint })
75
76
  export async function withHostedClient({ apiKey, restEndpoint, socketEndpoint, appSource, appId }, work) {
76
77
  await assertSafeSogniEndpoints({ restEndpoint, socketEndpoint });
77
78
  const client = await SogniClient.createInstance({
78
- appId: appId ?? `sogni-skill-${process.pid}-${Date.now()}`,
79
+ appId: appId ?? getOrCreateSogniAppId(),
79
80
  apiKey,
80
81
  appSource: appSource ?? 'sogni-creative-agent-skill',
81
82
  logLevel: 'error',
package/version.mjs CHANGED
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = '3.18.0';
1
+ export const PACKAGE_VERSION = '3.19.0';