inistate-mcp 1.0.3 → 1.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/README.md +49 -22
- package/build/activity-guard.d.ts +122 -0
- package/build/activity-guard.js +115 -16
- package/build/api.d.ts +18 -0
- package/build/api.js +24 -6
- package/build/backend.d.ts +170 -0
- package/build/backend.js +132 -0
- package/build/capability.d.ts +26 -0
- package/build/capability.js +42 -0
- package/build/context.d.ts +13 -0
- package/build/http.d.ts +6 -0
- package/build/http.js +1 -1
- package/build/index.d.ts +2 -0
- package/build/lib.d.ts +19 -0
- package/build/lib.js +18 -0
- package/build/mode-store.d.ts +12 -0
- package/build/oauth-provider.d.ts +40 -0
- package/build/oauth-provider.js +17 -0
- package/build/prompts.d.ts +4 -0
- package/build/resources.d.ts +6 -0
- package/build/resources.js +6 -7
- package/build/schema.d.ts +61 -0
- package/build/schema.js +332 -63
- package/build/server.d.ts +14 -0
- package/build/server.js +33 -8
- package/build/setup.d.ts +1 -0
- package/build/tools.d.ts +5 -0
- package/build/tools.js +569 -239
- package/inistate-schema.json +28 -11
- package/package.json +11 -4
- package/server.json +2 -2
package/README.md
CHANGED
|
@@ -10,6 +10,9 @@ MCP server for the [Inistate](https://inistate.com) platform — module discover
|
|
|
10
10
|
|----------|----------|---------|-------------|
|
|
11
11
|
| `INISTATE_API_TOKEN` | Yes | — | Bearer token for Inistate API authentication |
|
|
12
12
|
| `INISTATE_API_BASE` | No | `https://api.inistate.com` | API base URL |
|
|
13
|
+
| `INISTATE_MCP_MODE` | No | `configure` | Initial mode: `runtime`, `configure`, or `frontend` (see [Modes](#modes)) |
|
|
14
|
+
| `INISTATE_MCP_NO_SETUP` | No | — | Set to `1` to force server mode from a terminal (skip the interactive wizard) |
|
|
15
|
+
| `INISTATE_DEBUG_FILE` | No | — | Set to `1` to log write-path tool calls to `./debug.log`, or to a path to log there. Off by default; logs identifiers only, never field values |
|
|
13
16
|
|
|
14
17
|
### Install from npm (recommended)
|
|
15
18
|
|
|
@@ -77,24 +80,30 @@ Then point your MCP client at `node /absolute/path/to/inistate-mcp/build/index.j
|
|
|
77
80
|
|
|
78
81
|
## Tools
|
|
79
82
|
|
|
83
|
+
Tools marked **(configure)** are only exposed in configure mode — see [Modes](#modes).
|
|
84
|
+
|
|
80
85
|
| Tool | Description |
|
|
81
86
|
|------|-------------|
|
|
82
87
|
| `list_workspaces` | List workspaces the user has access to |
|
|
83
88
|
| `set_workspace` | Set the active workspace |
|
|
84
89
|
| `list_modules` | List all discoverable modules in the workspace |
|
|
85
|
-
| `get_module_schema` | Get the canvas schema (basic or extended tier) |
|
|
86
|
-
| `get_module_canvas` | Get full module definition with stable IDs (round-trippable) |
|
|
90
|
+
| `get_module_schema` | Get the canvas schema (basic or extended tier) **(configure)** |
|
|
91
|
+
| `get_module_canvas` | Get full module definition with stable IDs (round-trippable) **(configure)** |
|
|
87
92
|
| `list_entries` | Query entries with filters, sorting, and pagination |
|
|
88
93
|
| `get_entry` | Read a single entry by ID |
|
|
89
94
|
| `get_form` | Get form fields and defaults for an activity |
|
|
90
95
|
| `submit_activity` | Create, edit, delete, or run custom activities |
|
|
96
|
+
| `submit_activities` | Bulk variant — same activity applied to up to 100 entries in one call |
|
|
91
97
|
| `get_entry_history` | Get entry audit trail and comments |
|
|
92
|
-
| `
|
|
98
|
+
| `request_upload_url` | Default upload path — get a presigned S3 URL to PUT file bytes to |
|
|
99
|
+
| `confirm_upload` | Confirm a presigned upload completed; returns the File/Image field path |
|
|
100
|
+
| `upload_file` | Fallback upload via base64/multipart (use only if the presigned flow fails) |
|
|
93
101
|
| `download_file` | Download a file (returns pre-signed URL) |
|
|
94
|
-
| `design_workflow` | Generate a scaffolded module template from a description |
|
|
95
|
-
| `validate_design` | Validate a module schema before creating or updating |
|
|
96
|
-
| `create_module` | Create a new module with schema |
|
|
97
|
-
| `update_module` | Update an existing module's schema |
|
|
102
|
+
| `design_workflow` | Generate a scaffolded module template from a description **(configure)** |
|
|
103
|
+
| `validate_design` | Validate a module schema before creating or updating **(configure)** |
|
|
104
|
+
| `create_module` | Create a new module with schema **(configure)** |
|
|
105
|
+
| `update_module` | Update an existing module's schema **(configure)** |
|
|
106
|
+
| `switch_mode` | Switch the active mode (runtime / configure / frontend) |
|
|
98
107
|
|
|
99
108
|
## Resources
|
|
100
109
|
|
|
@@ -103,26 +112,41 @@ Then point your MCP client at `node /absolute/path/to/inistate-mcp/build/index.j
|
|
|
103
112
|
| `inistate://modules` | List all modules |
|
|
104
113
|
| `inistate://modules/{name}/canvas` | Basic module schema (fields + states) |
|
|
105
114
|
| `inistate://modules/{name}/canvas/extended` | Extended schema with activities and flows |
|
|
106
|
-
| `inistate://
|
|
107
|
-
| `inistate://
|
|
115
|
+
| `inistate://guardrails` | Server-enforced `submit_activity` rules (read once per session) |
|
|
116
|
+
| `inistate://schema/runtime` | Runtime schema — entry/activity/file types and filter operators (default) |
|
|
117
|
+
| `inistate://schema/configure` | Module-design schema — write format, field types, colors **(configure)** |
|
|
118
|
+
| `inistate://design-guide` | FACTS Module Design Guide **(configure)** |
|
|
119
|
+
| `inistate://frontend-guide` | REST API reference for hand-written UIs **(frontend)** |
|
|
108
120
|
|
|
109
121
|
## Prompts
|
|
110
122
|
|
|
111
123
|
| Prompt | Description |
|
|
112
124
|
|--------|-------------|
|
|
113
|
-
| `design_factsops_workflow` | Guide an agent through designing a complete workflow module |
|
|
125
|
+
| `design_factsops_workflow` | Guide an agent through designing a complete workflow module **(configure)** |
|
|
114
126
|
| `execute_activity` | Guide an agent through executing a specific activity |
|
|
115
127
|
| `diagnose_entry` | Guide an agent through investigating an entry's state and history |
|
|
128
|
+
| `modify_module` | Guide an agent through modifying an existing module's schema **(configure)** |
|
|
129
|
+
|
|
130
|
+
## Modes
|
|
131
|
+
|
|
132
|
+
The server exposes a focused tool/resource surface depending on the active mode, keeping agent context lean. Use `switch_mode` to change it, or set the initial mode via the `INISTATE_MCP_MODE` env var (default: `configure`).
|
|
133
|
+
|
|
134
|
+
| Mode | Surface |
|
|
135
|
+
|------|---------|
|
|
136
|
+
| `runtime` | Entry and activity operations only — querying, reading, submitting, files, history. The leanest surface for using existing modules. |
|
|
137
|
+
| `configure` | Everything in `runtime` plus the module-design tools, resources, and prompts (marked **(configure)** above). |
|
|
138
|
+
| `frontend` | Everything in `configure` plus the `inistate://frontend-guide` resource for building hand-written UIs against the REST API. |
|
|
139
|
+
|
|
140
|
+
Tools and resources marked **(configure)** / **(frontend)** are absent from the tool list in narrower modes — switch modes to reveal them.
|
|
116
141
|
|
|
117
142
|
## Typical Workflow
|
|
118
143
|
|
|
119
|
-
1. `list_workspaces` → `set_workspace` — select a workspace
|
|
120
|
-
2. `
|
|
121
|
-
3. `
|
|
122
|
-
4. `
|
|
123
|
-
5. `
|
|
124
|
-
6. `
|
|
125
|
-
7. `get_entry_history` — review entry history
|
|
144
|
+
1. `list_workspaces` → `set_workspace` — select a workspace (auto-selected when exactly one matches; both return the workspace's module list, so `list_modules` is only needed to refresh)
|
|
145
|
+
2. `get_module_schema` — understand a module's fields, states, and activities
|
|
146
|
+
3. `get_form` — discover required fields before the first submission per (module, activity); reuse its schema for further entries
|
|
147
|
+
4. `submit_activity` — create or update entries (`submit_activities` for bulk)
|
|
148
|
+
5. `list_entries` — query and browse data (use the `fields` parameter to keep payloads small)
|
|
149
|
+
6. `get_entry_history` — review entry history
|
|
126
150
|
|
|
127
151
|
## Development
|
|
128
152
|
|
|
@@ -231,8 +255,11 @@ Tests are in `src/` alongside the source files and use [Vitest](https://vitest.d
|
|
|
231
255
|
|
|
232
256
|
| File | Type | What it covers |
|
|
233
257
|
|------|------|----------------|
|
|
234
|
-
| `src/schema.test.ts` | Unit tests (
|
|
235
|
-
| `src/
|
|
258
|
+
| `src/schema.test.ts` | Unit tests (41) | `designWorkflow`, `validateDesign`, helper functions (`isValidFieldType`, `isValidColor`, `isValidActor`, `suggestColorForState`) |
|
|
259
|
+
| `src/activity-guard.test.ts` | Unit tests (35) | `submit_activity` guard rules — human/hybrid actor, state-change confirmation, confidence-inflation, reference-shape validation |
|
|
260
|
+
| `src/tools.schema.test.ts` | Unit tests (19) | Tool input-schema shapes and validation |
|
|
261
|
+
| `src/backend-capabilities.test.ts` | Unit tests (6) | Capability gating — Platform-only tools return a capability message on reduced backends |
|
|
262
|
+
| `src/server.test.ts` | Integration tests (15) | Spins up the MCP server as a child process and exercises it through the official MCP SDK client — mode-gated tool/resource/prompt discovery, `switch_mode`, resource reads, prompt retrieval, and local tool calls |
|
|
236
263
|
|
|
237
264
|
Unit tests cover:
|
|
238
265
|
- Field type and color validation against the schema
|
|
@@ -242,10 +269,10 @@ Unit tests cover:
|
|
|
242
269
|
- Intent resolution: all 5 modes, context boosting, confidence scoring
|
|
243
270
|
|
|
244
271
|
Integration tests verify (no API token needed):
|
|
245
|
-
- All
|
|
272
|
+
- All 20 tools, 8 resources, and 4 prompts are registered (in configure mode)
|
|
246
273
|
- `design_workflow`, `validate_design` work end-to-end through the MCP protocol
|
|
247
|
-
- Static resources (`inistate://schema`, `inistate://design-guide`) return valid content
|
|
248
|
-
- All
|
|
274
|
+
- Static resources (`inistate://schema/runtime`, `inistate://design-guide`) return valid content
|
|
275
|
+
- All 4 prompts return correctly templated messages
|
|
249
276
|
|
|
250
277
|
### Interactive testing with MCP Inspector
|
|
251
278
|
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pre-submission gate for `submit_activity`. Enforces four rules the platform
|
|
3
|
+
* does not enforce server-side:
|
|
4
|
+
*
|
|
5
|
+
* 1. Confidence inflation: once an activity has been flagged for human review
|
|
6
|
+
* (`flagged: true`), refuse subsequent submissions on the same target with
|
|
7
|
+
* a higher confidence unless the caller passes `confirmed: true`.
|
|
8
|
+
* 2. Explicit state changes (`changeStatus` activity, or an overriding `state`
|
|
9
|
+
* parameter) require `confirmed: true`.
|
|
10
|
+
* 3. Activities whose `actor` is `human` are never executable by an AI agent.
|
|
11
|
+
* 4. Activities whose `actor` is `hybrid` require `confirmed: true`.
|
|
12
|
+
*/
|
|
13
|
+
interface ActivityDef {
|
|
14
|
+
name: string;
|
|
15
|
+
actor?: string;
|
|
16
|
+
}
|
|
17
|
+
interface FieldInfo {
|
|
18
|
+
name: string;
|
|
19
|
+
type: string;
|
|
20
|
+
}
|
|
21
|
+
interface ExtendedSchema {
|
|
22
|
+
activities?: Array<ActivityDef | string>;
|
|
23
|
+
information?: FieldInfo[];
|
|
24
|
+
states?: Array<string | {
|
|
25
|
+
name?: string;
|
|
26
|
+
}>;
|
|
27
|
+
}
|
|
28
|
+
interface CanvasSchema {
|
|
29
|
+
activities?: ActivityDef[];
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Source of a module's extended schema. Defaults to the cloud API; the MCP tool
|
|
33
|
+
* handlers pass a backend-routed fetcher so the same guard runs against whatever
|
|
34
|
+
* backend is injected (cloud or local) instead of always hitting api.ts.
|
|
35
|
+
*/
|
|
36
|
+
export type SchemaFetcher = (moduleName: string) => Promise<ExtendedSchema | null>;
|
|
37
|
+
/**
|
|
38
|
+
* Warm the schema cache in the background (fire-and-forget). Called from
|
|
39
|
+
* get_form so the guard/shape lookups on the submit_activity that typically
|
|
40
|
+
* follows hit cache instead of paying an extra round trip ahead of the write.
|
|
41
|
+
*/
|
|
42
|
+
export declare function primeSchemaCache(moduleName: string, fetchSchema?: SchemaFetcher): void;
|
|
43
|
+
/**
|
|
44
|
+
* Seed the schema cache with an extended schema the caller already fetched
|
|
45
|
+
* (e.g. the get_module_schema tool's own tier=extended response), so the
|
|
46
|
+
* guard does not re-fetch what just passed through this process.
|
|
47
|
+
*/
|
|
48
|
+
export declare function seedSchemaCache(moduleName: string, schema: unknown): void;
|
|
49
|
+
/**
|
|
50
|
+
* Source of a module's canvas (actor data). Like SchemaFetcher, the tool
|
|
51
|
+
* handlers pass a backend-routed fetcher so the actor fallback works against
|
|
52
|
+
* whatever backend is injected; the default hits the cloud API.
|
|
53
|
+
*/
|
|
54
|
+
export type CanvasFetcher = (moduleName: string) => Promise<CanvasSchema | null>;
|
|
55
|
+
interface FlaggedRecord {
|
|
56
|
+
confidence: number;
|
|
57
|
+
at: number;
|
|
58
|
+
}
|
|
59
|
+
export declare function recordFlagged(moduleName: string, entryId: unknown, activity: string, confidence: number): void;
|
|
60
|
+
export declare function clearFlagged(moduleName: string, entryId: unknown, activity: string): void;
|
|
61
|
+
export declare function getPriorFlag(moduleName: string, entryId: unknown, activity: string): FlaggedRecord | undefined;
|
|
62
|
+
export interface GuardInput {
|
|
63
|
+
module: string;
|
|
64
|
+
activity: string;
|
|
65
|
+
entryId?: string | number;
|
|
66
|
+
entryIds?: Array<string | number>;
|
|
67
|
+
state?: string;
|
|
68
|
+
confidence: number;
|
|
69
|
+
confirmed?: boolean;
|
|
70
|
+
}
|
|
71
|
+
export type GuardOutcome = {
|
|
72
|
+
ok: true;
|
|
73
|
+
} | {
|
|
74
|
+
ok: false;
|
|
75
|
+
structured: Record<string, unknown>;
|
|
76
|
+
};
|
|
77
|
+
export declare function evaluateActivity(input: GuardInput, fetchSchema?: SchemaFetcher, fetchCanvas?: CanvasFetcher): Promise<GuardOutcome>;
|
|
78
|
+
export interface RefShapeError {
|
|
79
|
+
field: string;
|
|
80
|
+
type: string;
|
|
81
|
+
message: string;
|
|
82
|
+
received: unknown;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* State names for a module, from the cached extended schema. Tolerates both
|
|
86
|
+
* string[] and [{name}] shapes; null when unavailable (let the API decide).
|
|
87
|
+
*/
|
|
88
|
+
export declare function getModuleStates(moduleName: string, fetchSchema?: SchemaFetcher): Promise<string[] | null>;
|
|
89
|
+
/**
|
|
90
|
+
* Build a field-name → field-type map for a module. Returns null when the
|
|
91
|
+
* schema cannot be loaded (callers should let the server decide). The
|
|
92
|
+
* underlying schema is cached by getExtendedSchema, so repeat calls are cheap.
|
|
93
|
+
*
|
|
94
|
+
* Split out so bulk callers (submit_activities) can fetch once and reuse the
|
|
95
|
+
* map across items via validateInputShapesWith.
|
|
96
|
+
*/
|
|
97
|
+
export declare function getModuleFieldTypes(moduleName: string, fetchSchema?: SchemaFetcher): Promise<Map<string, string> | null>;
|
|
98
|
+
/**
|
|
99
|
+
* Synchronous shape check against a pre-built field-type map. Use this in
|
|
100
|
+
* bulk loops to avoid rebuilding the map per item. When `types` is null
|
|
101
|
+
* (schema unavailable), returns [] so the server makes the final call.
|
|
102
|
+
*/
|
|
103
|
+
export declare function validateInputShapesWith(types: Map<string, string> | null, input: Record<string, unknown> | undefined | null): RefShapeError[];
|
|
104
|
+
/**
|
|
105
|
+
* Validate that User/Module/Users/Modules fields in `input` carry the
|
|
106
|
+
* correct shape. Convenience wrapper around getModuleFieldTypes +
|
|
107
|
+
* validateInputShapesWith — use this for one-shot calls (submit_activity).
|
|
108
|
+
* Bulk callers should fetch the map once and use validateInputShapesWith
|
|
109
|
+
* directly.
|
|
110
|
+
*/
|
|
111
|
+
export declare function validateInputShapes(moduleName: string, input: Record<string, unknown> | undefined | null, fetchSchema?: SchemaFetcher): Promise<RefShapeError[]>;
|
|
112
|
+
/**
|
|
113
|
+
* Annotation merged into platform responses that carry `flagged: true`. The
|
|
114
|
+
* platform itself returns the bare flag with no explanation — without this,
|
|
115
|
+
* agents loop retrying with higher confidence or `confirmed: true`.
|
|
116
|
+
*/
|
|
117
|
+
export declare const FLAGGED_ANNOTATION: {
|
|
118
|
+
readonly flag_reason: "Flagged submissions are recorded as intentions pending human review — the state transition did NOT occur. Causes: ai.confidence below the activity's confidence_threshold, or the activity's actor does not permit AI execution.";
|
|
119
|
+
readonly agent_action: "Do not retry with a higher confidence. Report the flag to the user; a human can complete the activity in Inistate.";
|
|
120
|
+
};
|
|
121
|
+
export declare function __resetGuardCaches(): void;
|
|
122
|
+
export {};
|
package/build/activity-guard.js
CHANGED
|
@@ -3,6 +3,8 @@ import { requestContext } from "./context.js";
|
|
|
3
3
|
const REF_FIELD_TYPES = new Set(["User", "Users", "Module", "Modules"]);
|
|
4
4
|
// Standard activities are inherent platform operations and have no actor in the
|
|
5
5
|
// module schema. They bypass the actor check (but state-change checks still run).
|
|
6
|
+
// The platform uses both names for the direct state change — availableActivities
|
|
7
|
+
// lists "changeState" while forms and history say "changeStatus".
|
|
6
8
|
const STANDARD_ACTIVITIES = new Set([
|
|
7
9
|
"create",
|
|
8
10
|
"edit",
|
|
@@ -12,6 +14,7 @@ const STANDARD_ACTIVITIES = new Set([
|
|
|
12
14
|
"manage",
|
|
13
15
|
"view",
|
|
14
16
|
"changeStatus",
|
|
17
|
+
"changeState",
|
|
15
18
|
]);
|
|
16
19
|
const SCHEMA_TTL_MS = 5 * 60 * 1000;
|
|
17
20
|
const schemaCache = new Map();
|
|
@@ -21,24 +24,78 @@ function cacheKey(prefix, parts) {
|
|
|
21
24
|
const user = ctx?.userId || "_";
|
|
22
25
|
return [prefix, user, wsid, ...parts.map((p) => String(p ?? "_"))].join("::");
|
|
23
26
|
}
|
|
24
|
-
async
|
|
27
|
+
const defaultSchemaFetcher = async (moduleName) => {
|
|
28
|
+
try {
|
|
29
|
+
return (await api.get(`/api/mcp/${api.enc(moduleName)}?tier=extended`));
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
async function getExtendedSchema(moduleName, fetchSchema = defaultSchemaFetcher) {
|
|
25
36
|
const key = cacheKey("schema", [moduleName]);
|
|
26
37
|
const now = Date.now();
|
|
27
38
|
const cached = schemaCache.get(key);
|
|
28
39
|
if (cached && now - cached.at < SCHEMA_TTL_MS)
|
|
29
40
|
return cached.schema;
|
|
30
|
-
|
|
31
|
-
|
|
41
|
+
const schema = await fetchSchema(moduleName);
|
|
42
|
+
if (schema)
|
|
32
43
|
schemaCache.set(key, { schema, at: now });
|
|
33
|
-
|
|
44
|
+
return schema;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Warm the schema cache in the background (fire-and-forget). Called from
|
|
48
|
+
* get_form so the guard/shape lookups on the submit_activity that typically
|
|
49
|
+
* follows hit cache instead of paying an extra round trip ahead of the write.
|
|
50
|
+
*/
|
|
51
|
+
export function primeSchemaCache(moduleName, fetchSchema = defaultSchemaFetcher) {
|
|
52
|
+
void getExtendedSchema(moduleName, fetchSchema).catch(() => { });
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Seed the schema cache with an extended schema the caller already fetched
|
|
56
|
+
* (e.g. the get_module_schema tool's own tier=extended response), so the
|
|
57
|
+
* guard does not re-fetch what just passed through this process.
|
|
58
|
+
*/
|
|
59
|
+
export function seedSchemaCache(moduleName, schema) {
|
|
60
|
+
if (!schema || typeof schema !== "object")
|
|
61
|
+
return;
|
|
62
|
+
schemaCache.set(cacheKey("schema", [moduleName]), {
|
|
63
|
+
schema: schema,
|
|
64
|
+
at: Date.now(),
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
const canvasCache = new Map();
|
|
68
|
+
const defaultCanvasFetcher = async (moduleName) => {
|
|
69
|
+
try {
|
|
70
|
+
return (await api.get(`/api/configure/${api.enc(moduleName)}`));
|
|
34
71
|
}
|
|
35
72
|
catch {
|
|
36
73
|
return null;
|
|
37
74
|
}
|
|
75
|
+
};
|
|
76
|
+
async function getCanvasSchema(moduleName, fetchCanvas = defaultCanvasFetcher) {
|
|
77
|
+
const key = cacheKey("canvas", [moduleName]);
|
|
78
|
+
const now = Date.now();
|
|
79
|
+
const cached = canvasCache.get(key);
|
|
80
|
+
if (cached && now - cached.at < SCHEMA_TTL_MS)
|
|
81
|
+
return cached.canvas;
|
|
82
|
+
// Cache the miss too — a caller without configure access would otherwise
|
|
83
|
+
// pay a failing round trip on every submit.
|
|
84
|
+
const canvas = await fetchCanvas(moduleName);
|
|
85
|
+
canvasCache.set(key, { canvas, at: now });
|
|
86
|
+
return canvas;
|
|
38
87
|
}
|
|
39
|
-
async function getActivityDef(moduleName, activity) {
|
|
40
|
-
const schema = await getExtendedSchema(moduleName);
|
|
41
|
-
|
|
88
|
+
async function getActivityDef(moduleName, activity, fetchSchema = defaultSchemaFetcher, fetchCanvas = defaultCanvasFetcher) {
|
|
89
|
+
const schema = await getExtendedSchema(moduleName, fetchSchema);
|
|
90
|
+
for (const a of schema?.activities ?? []) {
|
|
91
|
+
if (a && typeof a === "object" && a.name === activity) {
|
|
92
|
+
if (a.actor)
|
|
93
|
+
return a;
|
|
94
|
+
break; // listed without actor info — consult the canvas
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const canvas = await getCanvasSchema(moduleName, fetchCanvas);
|
|
98
|
+
return canvas?.activities?.find((a) => a && typeof a === "object" && a.name === activity) ?? null;
|
|
42
99
|
}
|
|
43
100
|
const FLAG_TTL_MS = 60 * 60 * 1000;
|
|
44
101
|
const flaggedCache = new Map();
|
|
@@ -62,7 +119,7 @@ export function getPriorFlag(moduleName, entryId, activity) {
|
|
|
62
119
|
}
|
|
63
120
|
return rec;
|
|
64
121
|
}
|
|
65
|
-
export async function evaluateActivity(input) {
|
|
122
|
+
export async function evaluateActivity(input, fetchSchema = defaultSchemaFetcher, fetchCanvas = defaultCanvasFetcher) {
|
|
66
123
|
const { module: moduleName, activity, entryId, entryIds, state, confidence, confirmed } = input;
|
|
67
124
|
// Rule 1 — confidence inflation after a prior flag.
|
|
68
125
|
const targets = entryIds && entryIds.length > 0 ? entryIds : [entryId];
|
|
@@ -83,13 +140,31 @@ export async function evaluateActivity(input) {
|
|
|
83
140
|
};
|
|
84
141
|
}
|
|
85
142
|
}
|
|
86
|
-
// Rule
|
|
87
|
-
|
|
143
|
+
// Rule 2 pre-flight — a target state must exist before any confirmation
|
|
144
|
+
// dance. The platform returns an opaque error for unknown states.
|
|
145
|
+
if (state) {
|
|
146
|
+
const states = await getModuleStates(moduleName, fetchSchema);
|
|
147
|
+
if (states && !states.includes(state)) {
|
|
148
|
+
return {
|
|
149
|
+
ok: false,
|
|
150
|
+
structured: {
|
|
151
|
+
error: "unknown_state",
|
|
152
|
+
message: `State '${state}' does not exist on module '${moduleName}'. Available states: ${states.join(", ")}.`,
|
|
153
|
+
activity,
|
|
154
|
+
state,
|
|
155
|
+
agent_action: "Use one of the listed states, or omit 'state' to follow the activity's normal flow.",
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
// Rule 2a — `changeStatus` (alias `changeState`) is the explicit
|
|
161
|
+
// state-change override.
|
|
162
|
+
if ((activity === "changeStatus" || activity === "changeState") && !confirmed) {
|
|
88
163
|
return {
|
|
89
164
|
ok: false,
|
|
90
165
|
structured: {
|
|
91
166
|
error: "state_change_requires_confirmation",
|
|
92
|
-
message:
|
|
167
|
+
message: `The '${activity}' activity bypasses the workflow to change an entry's state directly. AI agents must not call it on their own initiative.`,
|
|
93
168
|
activity,
|
|
94
169
|
agent_action: "Ask the user explicitly whether to change the entry's state. After they confirm, resubmit with confirmed: true.",
|
|
95
170
|
},
|
|
@@ -111,7 +186,7 @@ export async function evaluateActivity(input) {
|
|
|
111
186
|
// Rules 3 & 4 apply to custom (workflow-defined) activities only.
|
|
112
187
|
if (STANDARD_ACTIVITIES.has(activity))
|
|
113
188
|
return { ok: true };
|
|
114
|
-
const def = await getActivityDef(moduleName, activity);
|
|
189
|
+
const def = await getActivityDef(moduleName, activity, fetchSchema, fetchCanvas);
|
|
115
190
|
if (!def)
|
|
116
191
|
return { ok: true }; // unknown activity — let the API decide.
|
|
117
192
|
const actor = (def.actor || "").toLowerCase();
|
|
@@ -202,6 +277,20 @@ function checkRefValue(field, type, value) {
|
|
|
202
277
|
}
|
|
203
278
|
return checkSingleRef(field, type, value);
|
|
204
279
|
}
|
|
280
|
+
/**
|
|
281
|
+
* State names for a module, from the cached extended schema. Tolerates both
|
|
282
|
+
* string[] and [{name}] shapes; null when unavailable (let the API decide).
|
|
283
|
+
*/
|
|
284
|
+
export async function getModuleStates(moduleName, fetchSchema = defaultSchemaFetcher) {
|
|
285
|
+
const schema = await getExtendedSchema(moduleName, fetchSchema);
|
|
286
|
+
const raw = schema?.states;
|
|
287
|
+
if (!Array.isArray(raw) || raw.length === 0)
|
|
288
|
+
return null;
|
|
289
|
+
const names = raw
|
|
290
|
+
.map((s) => (typeof s === "string" ? s : s?.name))
|
|
291
|
+
.filter((n) => typeof n === "string" && n.length > 0);
|
|
292
|
+
return names.length > 0 ? names : null;
|
|
293
|
+
}
|
|
205
294
|
/**
|
|
206
295
|
* Build a field-name → field-type map for a module. Returns null when the
|
|
207
296
|
* schema cannot be loaded (callers should let the server decide). The
|
|
@@ -210,8 +299,8 @@ function checkRefValue(field, type, value) {
|
|
|
210
299
|
* Split out so bulk callers (submit_activities) can fetch once and reuse the
|
|
211
300
|
* map across items via validateInputShapesWith.
|
|
212
301
|
*/
|
|
213
|
-
export async function getModuleFieldTypes(moduleName) {
|
|
214
|
-
const schema = await getExtendedSchema(moduleName);
|
|
302
|
+
export async function getModuleFieldTypes(moduleName, fetchSchema = defaultSchemaFetcher) {
|
|
303
|
+
const schema = await getExtendedSchema(moduleName, fetchSchema);
|
|
215
304
|
const info = schema?.information;
|
|
216
305
|
if (!info || info.length === 0)
|
|
217
306
|
return null;
|
|
@@ -248,14 +337,24 @@ export function validateInputShapesWith(types, input) {
|
|
|
248
337
|
* Bulk callers should fetch the map once and use validateInputShapesWith
|
|
249
338
|
* directly.
|
|
250
339
|
*/
|
|
251
|
-
export async function validateInputShapes(moduleName, input) {
|
|
340
|
+
export async function validateInputShapes(moduleName, input, fetchSchema = defaultSchemaFetcher) {
|
|
252
341
|
if (!input)
|
|
253
342
|
return [];
|
|
254
|
-
const types = await getModuleFieldTypes(moduleName);
|
|
343
|
+
const types = await getModuleFieldTypes(moduleName, fetchSchema);
|
|
255
344
|
return validateInputShapesWith(types, input);
|
|
256
345
|
}
|
|
346
|
+
/**
|
|
347
|
+
* Annotation merged into platform responses that carry `flagged: true`. The
|
|
348
|
+
* platform itself returns the bare flag with no explanation — without this,
|
|
349
|
+
* agents loop retrying with higher confidence or `confirmed: true`.
|
|
350
|
+
*/
|
|
351
|
+
export const FLAGGED_ANNOTATION = {
|
|
352
|
+
flag_reason: "Flagged submissions are recorded as intentions pending human review — the state transition did NOT occur. Causes: ai.confidence below the activity's confidence_threshold, or the activity's actor does not permit AI execution.",
|
|
353
|
+
agent_action: "Do not retry with a higher confidence. Report the flag to the user; a human can complete the activity in Inistate.",
|
|
354
|
+
};
|
|
257
355
|
// Test-only helpers.
|
|
258
356
|
export function __resetGuardCaches() {
|
|
259
357
|
schemaCache.clear();
|
|
358
|
+
canvasCache.clear();
|
|
260
359
|
flaggedCache.clear();
|
|
261
360
|
}
|
package/build/api.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export declare function setWorkspaceId(wsid: string): void;
|
|
2
|
+
export declare function getWorkspaceId(): string | null;
|
|
3
|
+
export declare function get(path: string): Promise<unknown>;
|
|
4
|
+
export declare function post(path: string, body?: unknown): Promise<unknown>;
|
|
5
|
+
export declare function put(path: string, body?: unknown): Promise<unknown>;
|
|
6
|
+
/**
|
|
7
|
+
* Upload a file via multipart/form-data.
|
|
8
|
+
*/
|
|
9
|
+
export declare function uploadFormData(path: string, formData: FormData): Promise<unknown>;
|
|
10
|
+
/**
|
|
11
|
+
* GET with manual redirect for download_file — returns redirect URL instead of following.
|
|
12
|
+
*/
|
|
13
|
+
export declare function getRaw(path: string): Promise<{
|
|
14
|
+
redirectUrl: string | null;
|
|
15
|
+
status: number;
|
|
16
|
+
body: unknown;
|
|
17
|
+
}>;
|
|
18
|
+
export declare function enc(s: string): string;
|
package/build/api.js
CHANGED
|
@@ -111,14 +111,32 @@ async function handleResponse(res) {
|
|
|
111
111
|
if (!text)
|
|
112
112
|
return null;
|
|
113
113
|
const data = JSON.parse(text);
|
|
114
|
-
// §14.8 — truncate large list responses to avoid blowing up agent context
|
|
115
|
-
|
|
114
|
+
// §14.8 — truncate large list responses to avoid blowing up agent context.
|
|
115
|
+
// Size-aware: keep as many items as fit the byte budget (a fixed item count
|
|
116
|
+
// either overshoots for wide rows or wastes refetches for narrow ones).
|
|
117
|
+
const TRUNCATE_BUDGET = 30_000;
|
|
118
|
+
if (text.length > TRUNCATE_BUDGET &&
|
|
116
119
|
data &&
|
|
117
120
|
typeof data === "object" &&
|
|
118
|
-
Array.isArray(data.list)
|
|
119
|
-
data.list
|
|
120
|
-
|
|
121
|
-
|
|
121
|
+
Array.isArray(data.list) &&
|
|
122
|
+
data.list.length > 1) {
|
|
123
|
+
const items = data.list;
|
|
124
|
+
const overhead = text.length - JSON.stringify(items).length;
|
|
125
|
+
const budget = Math.max(TRUNCATE_BUDGET - overhead, 2_000);
|
|
126
|
+
let size = 2;
|
|
127
|
+
let keep = 0;
|
|
128
|
+
for (const item of items) {
|
|
129
|
+
const itemLen = JSON.stringify(item).length + 1;
|
|
130
|
+
if (keep > 0 && size + itemLen > budget)
|
|
131
|
+
break;
|
|
132
|
+
size += itemLen;
|
|
133
|
+
keep++;
|
|
134
|
+
}
|
|
135
|
+
if (keep < items.length) {
|
|
136
|
+
data.list = items.slice(0, keep);
|
|
137
|
+
data._truncated = true;
|
|
138
|
+
data._truncated_message = `Response truncated to ${keep} of ${items.length} items on this page (~30KB cap; ${data.totalItems ?? "unknown"} total). Narrow the payload with the fields parameter (biggest saving) or filters, and paginate with currentPage/pageSize.`;
|
|
139
|
+
}
|
|
122
140
|
}
|
|
123
141
|
return data;
|
|
124
142
|
}
|