@niscorp/cortex 0.1.0 → 0.1.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 ADDED
@@ -0,0 +1,7 @@
1
+ # @niscorp/cortex
2
+
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - b67a125: Documentation only: each package's README, reference and design docs checked against its source and corrected — install lines and peers, signatures, defaults, status codes, licenses (loom, signal: Apache-2.0), and API that existed but was not documented.
package/DESIGN.md CHANGED
@@ -49,7 +49,7 @@ JSON-parsing of streams (solid), no event-bus substrate, no
49
49
  declarative rules DSL, no plan interpreter (§14), no conversation
50
50
  persistence (callers own history).
51
51
 
52
- **Peers:** `@niscorp/signal`, `@niscorp/solid`, `zod`.
52
+ **Peers:** `@niscorp/signal`, `zod`. **Dependency:** `@niscorp/solid`.
53
53
 
54
54
  ---
55
55
 
@@ -218,8 +218,8 @@ a content-only message.
218
218
  single-sourced from the same schema Zod validates against, so docs
219
219
  and validation cannot drift. When `respond` resolves to loose or
220
220
  permissive params (or strategy is `emit`), cortex injects
221
- `OUTPUT SCHEMA:\n…` as the
222
- last system chunk automatically. Agents that hand-author a full DSL
221
+ `OUTPUT SCHEMA …` as a
222
+ system chunk automatically (placement: §5). Agents that hand-author a full DSL
223
223
  guide (the architect pattern) disable it with `output.doc: 'off'` or
224
224
  replace it with a string.
225
225
 
@@ -232,7 +232,7 @@ prefix = assemble(context fns, input) — once, at run start
232
232
  messages = [...prefix] — append-only from here on
233
233
 
234
234
  step:
235
- stopWhen checks (steps, tokens, duration, outputRetries)
235
+ stopWhen checks (steps, tokens, duration, outputRetries, repeatedCalls)
236
236
  prepareStep hook → activeTools mask, toolChoice, injected messages, llm swap
237
237
  signal.stepStream({ messages, tools, responseFormat? })
238
238
  → model-delta events (text + reasoning channels)
@@ -274,9 +274,13 @@ Bounds are `stopWhen` predicates — one vocabulary instead of v1's
274
274
  maxToolIterations / maxTicks / maxDurationMs / budget tangle:
275
275
 
276
276
  ```ts
277
- stopWhen: [stepCount(20), tokens(100_000), duration('5m'), outputRetries(3)]
277
+ stopWhen: [stepCount(20), tokens(100_000), duration('5m'), outputRetries(3), repeatedCalls(3)]
278
278
  ```
279
279
 
280
+ `repeatedCalls(n)` ends a run whose model keeps sending the same tool
281
+ call and getting the same answer — every further step would cost a
282
+ full prompt and change nothing.
283
+
280
284
  Defaults: `stepCount(20)`, `outputRetries(3)`. No default duration or
281
285
  token cap — v1's 60-second default was overridden at every call site,
282
286
  which is what a wrong default looks like.
@@ -326,14 +330,19 @@ that is how knowledge drifts.
326
330
  agent's own — an app attaches shared knowledge to ANY agent without
327
331
  editing its definition.
328
332
  - **Tools bring their own guides.** `defineTool({ guide })` carries
329
- the tool's usage knowledge (a string or a deferred `() => string`,
333
+ the tool's usage knowledge (a string, a `string[]` of lines, or a
334
+ deferred function returning either,
330
335
  e.g. composing a library's exported guide). The run assembles one
331
336
  TOOL GUIDES section from the ACTIVE tools — add a tool and its
332
337
  guide arrives, change it and every agent updates, remove it and the
333
338
  guide leaves. Instructions never describe tools.
334
- - Prefix order: instructions → agent producers → run producers →
335
- tool guides → schema doc → finish protocol → input. The finish
336
- protocol is ONE cortex-owned chunk stating how the run ends under
339
+ - Prefix order: instructions → tool guides → schema doc → finish
340
+ protocol → agent producers → run producers → input. The three
341
+ middle blocks are fixed for the life of an agent, so they sit ahead
342
+ of the producers, which are not — a provider's prefix cache stops at
343
+ the first byte that changed. The finish
344
+ protocol is ONE chunk — authored by signal's transport, injected by
345
+ cortex verbatim — stating how the run ends under
337
346
  the RESOLVED transport (call `respond` / emit the envelope / reply
338
347
  under grammar) — agents never author finish lines; they cannot know
339
348
  which transport resolution picked.
@@ -348,7 +357,7 @@ that is how knowledge drifts.
348
357
  - Compaction (summarize-when-near-limit) is a future single hook on
349
358
  the transcript (§15), not a v1 pipeline.
350
359
 
351
- **Preview survives, better.** `agent.preview(input, { deps })`
360
+ **Preview survives, better.** `await agent.preview(input, { deps })`
352
361
  returns the exact assembled messages, the resolved tool list
353
362
  (including `respond` and its actual params), the resolved strategy,
354
363
  and a token estimate — no model call. Anything you can't explain in
@@ -372,10 +381,10 @@ type ToolGate<TDeps> = (call: ToolCallInfo, ctx: RunCtx<TDeps>) =>
372
381
  type ToolResultHook<TDeps> = (obs: ToolObservation, ctx: RunCtx<TDeps>) =>
373
382
  { result?: unknown } | void | Promise<…>; // replace / redact / truncate
374
383
 
375
- type PrepareStep<TDeps> = (s: StepInfo<TDeps>) =>
376
- { activeTools?: string[]; toolChoice?: ToolChoice; inject?: Message[]; llm?: SignalClient } | void;
384
+ type PrepareStep<TDeps> = (s: PrepareStepInfo<TDeps>) =>
385
+ { activeTools?: string[]; toolChoice?: ToolChoice; inject?: Message[]; llm?: SignalClient } | void | Promise<…>;
377
386
 
378
- type StopCondition = (s: RunProgress) => boolean;
387
+ type StopCondition = (s: RunProgress) => StopVerdict; // { stop: StopReason; message } | null
379
388
  ```
380
389
 
381
390
  - **Gates run before execution.** A deny reaches the model as a tool
@@ -438,7 +447,7 @@ const result = await run.result;
438
447
  | `model-delta` | `{ text, channel: 'text' \| 'reasoning' }` | provider reasoning tokens land here |
439
448
  | `tool-start` | `{ call }` | before gates + execution — drives live UIs |
440
449
  | `tool-end` | `{ observation }` | typed union incl. denials; no casting |
441
- | `approval-required` | `{ id, toolId, args, reason }` | run suspends |
450
+ | `approval-required` | `{ approval: { id, toolId, callId, args, reason } }` | run suspends |
442
451
  | `output-delta` | `{ text }` | raw envelope JSON fragments |
443
452
  | `output-partial` | `{ output }` | solid-parsed partial envelope |
444
453
  | `retry` | `{ kind: 'output' \| 'termination' \| 'provider', attempt, issues }` | consumers reset partial state; `issues` carries the evidence (Zod issues, the rejected attempt, or the stray text) |
@@ -503,10 +512,12 @@ Same two principles as v1, smaller taxonomy:
503
512
  ```ts
504
513
  type CortexError = {
505
514
  code: 'model_call_failed' | 'output_invalid' | 'stopped' | 'aborted' | 'unknown';
506
- stop?: 'steps' | 'tokens' | 'duration' | 'output_retries' | 'custom'; // when code === 'stopped'
515
+ stop?: StopReason; // when code === 'stopped':
516
+ // 'steps' | 'tokens' | 'duration' | 'output_retries' | 'repeated_calls' | 'custom'
507
517
  message: string;
508
518
  runId: string;
509
519
  agentPath: ReadonlyArray<string>;
520
+ lastOutput?: unknown; // the last invalid output when the run died on output retries
510
521
  cause?: unknown;
511
522
  };
512
523
  ```
@@ -519,7 +530,7 @@ principle as every other tool denial.
519
530
 
520
531
  ## 10. Streaming
521
532
 
522
- Always on (§4). Solid is a peer dependency and powers
533
+ Always on (§4). Solid is a dependency and powers
523
534
  `output-partial`: `respond` arg deltas (or content deltas under
524
535
  `native`/`emit`) stream through solid's partial parser into
525
536
  progressively-typed envelopes — a chat `response` string streams
@@ -538,36 +549,43 @@ defineTool(config): ToolDefinition // v1 shape, kept
538
549
  schemaDoc(schema, opts?): string
539
550
 
540
551
  // execution
541
- agent.run(input, { deps, llm?, tools?, gates?, onToolResult?, onEvent?, signal? }): RunHandle<TData>
552
+ agent.run(input, { deps, llm?, tools?, producers?, gates?, onToolResult?, onEvent?, signal? }): RunHandle<TData>
542
553
  // tools: per-run tools whose execute closes over per-invocation
543
554
  // dependencies (vex builds its query tools around the caller's
544
555
  // adapter + schema); appended to the agent's static tools.
545
- agent.preview(input, { deps }): ResolvedPreview
556
+ agent.preview(input, { deps }): Promise<ResolvedPreview>
546
557
  resumeRun(agent, snapshot, opts): RunHandle<TData>
547
558
 
548
559
  // RunHandle
549
560
  run.events: AsyncIterable<CortexEvent>
561
+ run.onEvent(listener): Unsubscribe
550
562
  run.result: Promise<RunResult<TData>>
551
563
  run.approve(id, { args? }) / run.deny(id, reason?)
552
564
  run.snapshot(): RunSnapshot
553
565
  run.abort(reason?)
554
566
 
555
567
  // composition
556
- createManifold({ llm, gates?, onRun? }): Manifold
557
- manifold.register / run / asTool / preview
568
+ createManifold({ llm?, gates?, onRun? }): Manifold
569
+ manifold.register / run / asTool / preview / agent / tool / agents / tools
570
+ asTool(agent, { id?, description?, llm?, timeoutMs?, deps, select? }): ToolDefinition
571
+
572
+ // gates
573
+ policyGate(policy): ToolGate
558
574
 
559
575
  // stop conditions
560
- stepCount(n), tokens(n), duration(ms | '5m'), outputRetries(n)
576
+ stepCount(n), tokens(n), duration(ms | '5m'), outputRetries(n), repeatedCalls(n)
577
+ DEFAULT_STOP_CONDITIONS // [stepCount(20), outputRetries(3)]
561
578
  ```
562
579
 
563
580
  `defineAgent` config:
564
581
 
565
582
  ```ts
566
583
  {
567
- id, description,
568
- llm?, // per-agent binding; manifold/run option is fallback
584
+ id, description?,
585
+ llm?, // per-agent binding; run option overrides it, manifold is the fallback
586
+ transport?: 'stream' | 'step', // default 'stream'; 'step' makes non-streaming calls (no deltas, no partials)
569
587
  instructions, // string | (ctx) => string — sugar for the first producer
570
- context?: Producer<TDeps>[], // compose shared sets by spreading: [...appProducers(), …]
588
+ context?: (ContextEntry | Producer<TDeps>)[], // compose shared sets by spreading: [...appProducers(), …]
571
589
  tools?: ToolDefinition[], // definitions, not id strings; each may carry its own `guide`
572
590
  output?: {
573
591
  schema?: ZodType<TData>, // omitted → pure chat agent (data: undefined)
@@ -585,6 +603,9 @@ stepCount(n), tokens(n), duration(ms | '5m'), outputRetries(n)
585
603
 
586
604
  ## 12. Signal changes this design requires
587
605
 
606
+ Items 1–3 are built; the text below is the requirement as it was
607
+ written. The tokenizer in item 4 has not landed.
608
+
588
609
  1. **`stepStream` emits `tool-call-delta`** — `{ index, id?, name?,
589
610
  argsText }` fragments as function args stream. The SSE chunks
590
611
  already contain them; the adapter currently drops them. This is
@@ -657,20 +678,20 @@ src/
657
678
  ├── types.ts # shared core types
658
679
  │
659
680
  ├── schemas/
660
- │ ├── envelope.schema.ts # Envelope<TData> factory
661
- │ ├── agent-config.schema.ts
681
+ │ ├── index.ts
682
+ │ ├── envelope.schema.ts # envelope wire / accept schemas, validateEnvelope
662
683
  │ └── tool-config.schema.ts
663
684
  │
664
685
  ├── agent/
665
686
  │ ├── define-agent.ts
666
- │ ├── run.ts # RunHandle, resumeRun
687
+ │ ├── run.ts # RunHandle, resumeRun, prefix assembly
667
688
  │ └── preview.ts
668
689
  │
669
690
  ├── loop/
670
691
  │ ├── loop.ts # the loop (§4) — all three transports
671
- │ ├── strategy-resolve.ts # auto resolution + strict-compat walk
672
- │ ├── respond-tool.ts # synthetic respond descriptor + corrections
673
692
  │ └── partials.ts # solid partial-output tracking
693
+ │ # (auto resolution, the strict-compat walk, the respond
694
+ │ # descriptor and corrections are signal's: src/transport/)
674
695
  │
675
696
  ├── context/
676
697
  │ ├── assemble.ts
@@ -679,15 +700,17 @@ src/
679
700
  ├── gates/
680
701
  │ ├── types.ts
681
702
  │ ├── policy.ts # sugar → built-in gate
682
- │ └── approval.ts # suspend / approve / deny / snapshot
703
+ │ ├── stop.ts # stop conditions + defaults
704
+ │ └── approval.ts # suspend / approve / deny
683
705
  │
684
706
  ├── events/
685
707
  │ ├── types.ts # CortexEvent vocabulary
686
- │ └── stream.ts # per-run emitter + forwarding
708
+ │ └── channel.ts # per-run emitter + forwarding
687
709
  │
688
710
  ├── manifold/
689
711
  │ ├── manifold.ts
690
- │ └── as-tool.ts
712
+ │ ├── as-tool.ts
713
+ │ └── types.ts # erased agent shapes
691
714
  │
692
715
  ├── tool/define-tool.ts
693
716
  ├── errors/cortex.errors.ts
package/README.md CHANGED
@@ -264,7 +264,7 @@ conditions return:
264
264
  ```ts
265
265
  type CortexError = {
266
266
  code: 'model_call_failed' | 'output_invalid' | 'stopped' | 'aborted' | 'unknown';
267
- stop?: 'steps' | 'tokens' | 'duration' | 'output_retries' | 'custom';
267
+ stop?: 'steps' | 'tokens' | 'duration' | 'output_retries' | 'repeated_calls' | 'custom';
268
268
  message: string;
269
269
  runId: string;
270
270
  agentPath: ReadonlyArray<string>;
@@ -281,7 +281,7 @@ them and decides; the run fails only on structural conditions.
281
281
  ```bash
282
282
  pnpm build # tsup ESM + CJS + DTS
283
283
  pnpm test # vitest run — scripted SignalClient stub, no network
284
- pnpm typecheck # tsc on src
284
+ pnpm typecheck # tsc on src + test
285
285
  ```
286
286
 
287
287
  ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@niscorp/cortex",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Agent runtime — one tool loop, typed envelopes, gates, streamed events",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -38,7 +38,7 @@
38
38
  },
39
39
  "peerDependencies": {
40
40
  "zod": "^4.2.0",
41
- "@niscorp/signal": "^0.1.0"
41
+ "@niscorp/signal": "^0.1.1"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@types/node": "^22.10.2",
@@ -46,7 +46,7 @@
46
46
  "tsx": "^4.19.2",
47
47
  "vitest": "^4.1.2",
48
48
  "zod": "^4.6.5",
49
- "@niscorp/signal": "0.1.0"
49
+ "@niscorp/signal": "0.1.1"
50
50
  },
51
51
  "scripts": {
52
52
  "build": "tsup",