snow-flow 4.0.3 → 4.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.
Files changed (39) hide show
  1. package/README.md +15 -40
  2. package/dist/cli.js +0 -81
  3. package/dist/dynamic-version.js +1 -1
  4. package/dist/index.js +3 -1
  5. package/dist/intelligence/performance-recommendations-engine.js +1 -0
  6. package/dist/mcp/servicenow-local-development-mcp.d.ts +0 -3
  7. package/dist/mcp/servicenow-local-development-mcp.js +7 -204
  8. package/dist/memory/snow-flow-memory-patterns.d.ts +29 -30
  9. package/dist/memory/snow-flow-memory-patterns.js +26 -37
  10. package/dist/snow-flow-system.js +1 -0
  11. package/dist/testing/integration-test-suite.js +1 -0
  12. package/dist/utils/artifact-local-sync.js +0 -17
  13. package/dist/utils/artifact-sync/artifact-registry.js +10 -10
  14. package/dist/utils/smart-field-fetcher.js +4 -6
  15. package/package.json +2 -2
  16. package/dist/agent/interactive.d.ts +0 -11
  17. package/dist/agent/interactive.js +0 -190
  18. package/dist/agent/session.d.ts +0 -12
  19. package/dist/agent/session.js +0 -106
  20. package/dist/cli/auth.d.ts +0 -3
  21. package/dist/cli/auth.js +0 -59
  22. package/dist/cli/session.d.ts +0 -3
  23. package/dist/cli/session.js +0 -46
  24. package/dist/llm/keys.d.ts +0 -5
  25. package/dist/llm/keys.js +0 -29
  26. package/dist/llm/providers.d.ts +0 -11
  27. package/dist/llm/providers.js +0 -77
  28. package/dist/mcp/bridge.d.ts +0 -10
  29. package/dist/mcp/bridge.js +0 -31
  30. package/dist/mcp/shared/mcp-types.d.ts +0 -37
  31. package/dist/mcp/shared/mcp-types.js +0 -7
  32. package/dist/memory/hierarchical-memory-system.d.ts +0 -32
  33. package/dist/memory/hierarchical-memory-system.js +0 -60
  34. package/dist/memory/memory-system.d.ts +0 -25
  35. package/dist/memory/memory-system.js +0 -36
  36. package/dist/session/store.d.ts +0 -47
  37. package/dist/session/store.js +0 -74
  38. package/dist/utils/chunking-manager.d.ts +0 -39
  39. package/dist/utils/chunking-manager.js +0 -142
@@ -1,11 +0,0 @@
1
- import type { SnowFlowConfig } from '../config/llm-config-loader';
2
- export type ProviderId = SnowFlowConfig['llm']['provider'];
3
- export interface ProviderOptions {
4
- provider: ProviderId;
5
- model: string;
6
- baseURL?: string;
7
- apiKeyEnv?: string;
8
- extraBody?: Record<string, unknown>;
9
- }
10
- export declare function getModel(opts: ProviderOptions): unknown;
11
- //# sourceMappingURL=providers.d.ts.map
@@ -1,77 +0,0 @@
1
- "use strict";
2
- // Compile-safe placeholder registry. Real providers will be wired via AI SDK in a follow-up step.
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.getModel = getModel;
5
- const keys_js_1 = require("./keys.js");
6
- function getModel(opts) {
7
- const { provider, model, baseURL, apiKeyEnv, extraBody } = opts;
8
- const requireOrThrow = (name) => {
9
- try {
10
- // eslint-disable-next-line @typescript-eslint/no-var-requires
11
- return require(name);
12
- }
13
- catch (err) {
14
- const hint = `Missing dependency ${name}. Run: npm i ai @ai-sdk/openai @ai-sdk/google @openrouter/ai-sdk-provider`;
15
- throw new Error(hint);
16
- }
17
- };
18
- switch (provider) {
19
- case 'anthropic': {
20
- // Prefer AI SDK anthropic provider if installed; otherwise instruct
21
- try {
22
- // Dynamic require to avoid hard dep
23
- const anthropic = require('@ai-sdk/anthropic');
24
- const key = process.env[apiKeyEnv || 'ANTHROPIC_API_KEY'] || (0, keys_js_1.getApiKey)('anthropic');
25
- if (!key)
26
- throw new Error('Missing ANTHROPIC_API_KEY');
27
- return anthropic.anthropic({ apiKey: key, baseURL }).languageModel(model);
28
- }
29
- catch (e) {
30
- throw new Error('Anthropic provider not available. Install @ai-sdk/anthropic or use OpenRouter with an Anthropic model.');
31
- }
32
- }
33
- case 'openai': {
34
- const { openai } = requireOrThrow('@ai-sdk/openai');
35
- const apiKey = process.env[apiKeyEnv || 'OPENAI_API_KEY'] || (0, keys_js_1.getApiKey)('openai');
36
- if (!apiKey)
37
- throw new Error('Missing OPENAI_API_KEY');
38
- return openai({ apiKey, baseURL }).languageModel(model);
39
- }
40
- case 'google': {
41
- const { google } = requireOrThrow('@ai-sdk/google');
42
- const apiKey = process.env[apiKeyEnv || 'GOOGLE_API_KEY']
43
- || process.env['GOOGLE_GENERATIVE_AI_API_KEY']
44
- || (0, keys_js_1.getApiKey)('google');
45
- if (!apiKey)
46
- throw new Error('Missing GOOGLE_API_KEY or GOOGLE_GENERATIVE_AI_API_KEY');
47
- return google({ apiKey, baseURL }).languageModel(model);
48
- }
49
- case 'openrouter': {
50
- const { createOpenRouter } = requireOrThrow('@openrouter/ai-sdk-provider');
51
- const apiKey = process.env[apiKeyEnv || 'OPENROUTER_API_KEY'] || (0, keys_js_1.getApiKey)('openrouter');
52
- if (!apiKey)
53
- throw new Error('Missing OPENROUTER_API_KEY');
54
- const or = createOpenRouter({ apiKey, baseURL, extraBody });
55
- return or(model);
56
- }
57
- case 'openai-compatible': {
58
- const { openai } = requireOrThrow('@ai-sdk/openai');
59
- const keyName = apiKeyEnv || 'OPENAI_COMPAT_API_KEY';
60
- const apiKey = process.env[keyName] || (0, keys_js_1.getApiKey)('openai-compatible');
61
- if (!baseURL)
62
- throw new Error('openai-compatible requires baseURL');
63
- if (!apiKey)
64
- throw new Error(`Missing ${keyName}`);
65
- return openai({ apiKey, baseURL }).languageModel(model);
66
- }
67
- case 'ollama': {
68
- const { openai } = requireOrThrow('@ai-sdk/openai');
69
- const keyName = apiKeyEnv || 'OLLAMA_API_KEY';
70
- const apiKey = process.env[keyName] || (0, keys_js_1.getApiKey)('ollama');
71
- if (!baseURL)
72
- throw new Error('ollama requires baseURL (e.g., http://localhost:11434/v1)');
73
- return openai({ apiKey, baseURL }).languageModel(model);
74
- }
75
- }
76
- }
77
- //# sourceMappingURL=providers.js.map
@@ -1,10 +0,0 @@
1
- export interface MCPStartup {
2
- cmd: string;
3
- args?: string[];
4
- env?: Record<string, string>;
5
- }
6
- export declare function loadMCPTools(start: MCPStartup): Promise<{
7
- tools: any[];
8
- close: () => Promise<void>;
9
- }>;
10
- //# sourceMappingURL=bridge.d.ts.map
@@ -1,31 +0,0 @@
1
- "use strict";
2
- // Minimal MCP bridge placeholder. We will hook this into AI SDK tools in a next step.
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.loadMCPTools = loadMCPTools;
5
- async function loadMCPTools(start) {
6
- // Prefer using AI SDK's experimental MCP client to yield ready-to-use Tool[]
7
- try {
8
- // eslint-disable-next-line @typescript-eslint/no-var-requires
9
- const { experimental_createMCPClient } = require('ai');
10
- // Use SDK-provided stdio transport
11
- // eslint-disable-next-line @typescript-eslint/no-var-requires
12
- const { StdioClientTransport } = require('@modelcontextprotocol/sdk/client/stdio');
13
- const client = await experimental_createMCPClient({
14
- name: 'snow-flow',
15
- transport: new StdioClientTransport({
16
- command: start.cmd,
17
- args: start.args ?? [],
18
- env: start.env ?? {},
19
- }),
20
- });
21
- const tools = await client.tools();
22
- return { tools, close: client.close };
23
- }
24
- catch (err) {
25
- // Fallback: no AI SDK available, return empty tools and noop close but with a hint.
26
- const hint = 'AI SDK MCP bridge not available. Install "ai" or verify version to enable MCP tools.';
27
- console.warn(`[snow-flow] ${hint}`);
28
- return { tools: [], close: async () => { } };
29
- }
30
- }
31
- //# sourceMappingURL=bridge.js.map
@@ -1,37 +0,0 @@
1
- /**
2
- * MCP Types
3
- * Common types for MCP server implementations
4
- */
5
- export interface MCPServerConfig {
6
- name: string;
7
- description?: string;
8
- version?: string;
9
- }
10
- export interface MCPTool {
11
- name: string;
12
- description: string;
13
- inputSchema: any;
14
- }
15
- export interface MCPResponse<T = any> {
16
- success: boolean;
17
- data?: T;
18
- error?: string;
19
- message?: string;
20
- }
21
- export interface MCPRequest {
22
- tool: string;
23
- params: any;
24
- }
25
- export interface MCPLogger {
26
- info(message: string, meta?: any): void;
27
- warn(message: string, meta?: any): void;
28
- error(message: string, meta?: any): void;
29
- debug(message: string, meta?: any): void;
30
- }
31
- export interface MCPMemoryManager {
32
- store(key: string, value: any): Promise<void>;
33
- retrieve(key: string): Promise<any>;
34
- delete(key: string): Promise<boolean>;
35
- list(): Promise<string[]>;
36
- }
37
- //# sourceMappingURL=mcp-types.d.ts.map
@@ -1,7 +0,0 @@
1
- "use strict";
2
- /**
3
- * MCP Types
4
- * Common types for MCP server implementations
5
- */
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- //# sourceMappingURL=mcp-types.js.map
@@ -1,32 +0,0 @@
1
- /**
2
- * Hierarchical Memory System
3
- * Extended memory system with hierarchical organization
4
- */
5
- import { MemorySystem } from './memory-system';
6
- export interface HierarchicalMemorySystem extends MemorySystem {
7
- dbPath?: string;
8
- namespace?: string;
9
- storeInNamespace(namespace: string, key: string, value: any): Promise<void>;
10
- retrieveFromNamespace(namespace: string, key: string): Promise<any>;
11
- listNamespaces(): Promise<string[]>;
12
- clearNamespace(namespace: string): Promise<void>;
13
- }
14
- export declare class DefaultHierarchicalMemorySystem implements HierarchicalMemorySystem {
15
- private memory;
16
- dbPath?: string;
17
- namespace?: string;
18
- constructor(dbPath?: string, namespace?: string);
19
- private getNamespaceMap;
20
- store(key: string, value: any): Promise<void>;
21
- retrieve(key: string): Promise<any>;
22
- get(key: string): Promise<any>;
23
- delete(key: string): Promise<boolean>;
24
- clear(): Promise<void>;
25
- list(): Promise<string[]>;
26
- exists(key: string): Promise<boolean>;
27
- storeInNamespace(namespace: string, key: string, value: any): Promise<void>;
28
- retrieveFromNamespace(namespace: string, key: string): Promise<any>;
29
- listNamespaces(): Promise<string[]>;
30
- clearNamespace(namespace: string): Promise<void>;
31
- }
32
- //# sourceMappingURL=hierarchical-memory-system.d.ts.map
@@ -1,60 +0,0 @@
1
- "use strict";
2
- /**
3
- * Hierarchical Memory System
4
- * Extended memory system with hierarchical organization
5
- */
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.DefaultHierarchicalMemorySystem = void 0;
8
- class DefaultHierarchicalMemorySystem {
9
- constructor(dbPath, namespace) {
10
- this.memory = new Map();
11
- this.dbPath = dbPath;
12
- this.namespace = namespace || 'default';
13
- }
14
- getNamespaceMap(namespace) {
15
- if (!this.memory.has(namespace)) {
16
- this.memory.set(namespace, new Map());
17
- }
18
- return this.memory.get(namespace);
19
- }
20
- async store(key, value) {
21
- await this.storeInNamespace(this.namespace || 'default', key, value);
22
- }
23
- async retrieve(key) {
24
- return this.retrieveFromNamespace(this.namespace || 'default', key);
25
- }
26
- async get(key) {
27
- return this.retrieve(key);
28
- }
29
- async delete(key) {
30
- const nsMap = this.getNamespaceMap(this.namespace || 'default');
31
- return nsMap.delete(key);
32
- }
33
- async clear() {
34
- await this.clearNamespace(this.namespace || 'default');
35
- }
36
- async list() {
37
- const nsMap = this.getNamespaceMap(this.namespace || 'default');
38
- return Array.from(nsMap.keys());
39
- }
40
- async exists(key) {
41
- const nsMap = this.getNamespaceMap(this.namespace || 'default');
42
- return nsMap.has(key);
43
- }
44
- async storeInNamespace(namespace, key, value) {
45
- const nsMap = this.getNamespaceMap(namespace);
46
- nsMap.set(key, value);
47
- }
48
- async retrieveFromNamespace(namespace, key) {
49
- const nsMap = this.getNamespaceMap(namespace);
50
- return nsMap.get(key);
51
- }
52
- async listNamespaces() {
53
- return Array.from(this.memory.keys());
54
- }
55
- async clearNamespace(namespace) {
56
- this.memory.delete(namespace);
57
- }
58
- }
59
- exports.DefaultHierarchicalMemorySystem = DefaultHierarchicalMemorySystem;
60
- //# sourceMappingURL=hierarchical-memory-system.js.map
@@ -1,25 +0,0 @@
1
- /**
2
- * Basic Memory System Interface
3
- * Minimal implementation to satisfy missing imports
4
- */
5
- export interface MemorySystem {
6
- store(key: string, value: any): Promise<void>;
7
- retrieve(key: string): Promise<any>;
8
- get(key: string): Promise<any>;
9
- delete(key: string): Promise<boolean>;
10
- clear(): Promise<void>;
11
- list(): Promise<string[]>;
12
- exists(key: string): Promise<boolean>;
13
- }
14
- export declare class BasicMemorySystem implements MemorySystem {
15
- private memory;
16
- store(key: string, value: any): Promise<void>;
17
- retrieve(key: string): Promise<any>;
18
- get(key: string): Promise<any>;
19
- delete(key: string): Promise<boolean>;
20
- clear(): Promise<void>;
21
- list(): Promise<string[]>;
22
- exists(key: string): Promise<boolean>;
23
- }
24
- export declare const defaultMemorySystem: BasicMemorySystem;
25
- //# sourceMappingURL=memory-system.d.ts.map
@@ -1,36 +0,0 @@
1
- "use strict";
2
- /**
3
- * Basic Memory System Interface
4
- * Minimal implementation to satisfy missing imports
5
- */
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.defaultMemorySystem = exports.BasicMemorySystem = void 0;
8
- class BasicMemorySystem {
9
- constructor() {
10
- this.memory = new Map();
11
- }
12
- async store(key, value) {
13
- this.memory.set(key, value);
14
- }
15
- async retrieve(key) {
16
- return this.memory.get(key);
17
- }
18
- async get(key) {
19
- return this.memory.get(key);
20
- }
21
- async delete(key) {
22
- return this.memory.delete(key);
23
- }
24
- async clear() {
25
- this.memory.clear();
26
- }
27
- async list() {
28
- return Array.from(this.memory.keys());
29
- }
30
- async exists(key) {
31
- return this.memory.has(key);
32
- }
33
- }
34
- exports.BasicMemorySystem = BasicMemorySystem;
35
- exports.defaultMemorySystem = new BasicMemorySystem();
36
- //# sourceMappingURL=memory-system.js.map
@@ -1,47 +0,0 @@
1
- export interface SessionMessage {
2
- role: 'system' | 'user' | 'assistant' | 'tool';
3
- content: string;
4
- timestamp: string;
5
- meta?: Record<string, unknown>;
6
- }
7
- export interface SessionRecord {
8
- id: string;
9
- startedAt: string;
10
- endedAt?: string;
11
- objective: string;
12
- provider: {
13
- id: string;
14
- model: string;
15
- baseURL?: string;
16
- };
17
- mcp: {
18
- cmd: string;
19
- args?: string[];
20
- };
21
- messages: SessionMessage[];
22
- toolEvents?: {
23
- name: string;
24
- when: string;
25
- argsPreview?: string;
26
- resultPreview?: string;
27
- }[];
28
- summary?: string;
29
- }
30
- export declare function createSessionId(): string;
31
- export declare function startSession(rec: Omit<SessionRecord, 'messages' | 'toolEvents'> & {
32
- messages?: SessionMessage[];
33
- }): SessionRecord;
34
- export declare function readSession(id: string): SessionRecord | undefined;
35
- export declare function listSessions(): {
36
- id: string;
37
- startedAt: string;
38
- objective: string;
39
- }[];
40
- export declare function appendMessage(id: string, msg: SessionMessage): void;
41
- export declare function appendToolEvent(id: string, ev: {
42
- name: string;
43
- argsPreview?: string;
44
- resultPreview?: string;
45
- }): void;
46
- export declare function endSession(id: string, summary?: string): void;
47
- //# sourceMappingURL=store.d.ts.map
@@ -1,74 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.createSessionId = createSessionId;
7
- exports.startSession = startSession;
8
- exports.readSession = readSession;
9
- exports.listSessions = listSessions;
10
- exports.appendMessage = appendMessage;
11
- exports.appendToolEvent = appendToolEvent;
12
- exports.endSession = endSession;
13
- const fs_1 = __importDefault(require("fs"));
14
- const os_1 = __importDefault(require("os"));
15
- const path_1 = __importDefault(require("path"));
16
- function ensureDir(dir) {
17
- if (!fs_1.default.existsSync(dir))
18
- fs_1.default.mkdirSync(dir, { recursive: true });
19
- }
20
- function sessionsDir() {
21
- const dir = path_1.default.join(os_1.default.homedir(), '.snow-flow', 'sessions');
22
- ensureDir(dir);
23
- return dir;
24
- }
25
- function createSessionId() {
26
- return `sess_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
27
- }
28
- function sessionPath(id) {
29
- return path_1.default.join(sessionsDir(), `${id}.json`);
30
- }
31
- function startSession(rec) {
32
- const full = { ...rec, messages: rec.messages ?? [], toolEvents: [] };
33
- fs_1.default.writeFileSync(sessionPath(rec.id), JSON.stringify(full, null, 2), 'utf8');
34
- return full;
35
- }
36
- function readSession(id) {
37
- const p = sessionPath(id);
38
- if (!fs_1.default.existsSync(p))
39
- return undefined;
40
- return JSON.parse(fs_1.default.readFileSync(p, 'utf8'));
41
- }
42
- function listSessions() {
43
- const dir = sessionsDir();
44
- const files = fs_1.default.readdirSync(dir).filter(f => f.endsWith('.json'));
45
- return files.map(f => {
46
- const rec = JSON.parse(fs_1.default.readFileSync(path_1.default.join(dir, f), 'utf8'));
47
- return { id: rec.id, startedAt: rec.startedAt, objective: rec.objective };
48
- }).sort((a, b) => (a.startedAt < b.startedAt ? 1 : -1));
49
- }
50
- function appendMessage(id, msg) {
51
- const rec = readSession(id);
52
- if (!rec)
53
- return;
54
- rec.messages.push(msg);
55
- fs_1.default.writeFileSync(sessionPath(id), JSON.stringify(rec, null, 2), 'utf8');
56
- }
57
- function appendToolEvent(id, ev) {
58
- const rec = readSession(id);
59
- if (!rec)
60
- return;
61
- const item = { name: ev.name, when: new Date().toISOString(), argsPreview: ev.argsPreview, resultPreview: ev.resultPreview };
62
- (rec.toolEvents = rec.toolEvents || []).push(item);
63
- fs_1.default.writeFileSync(sessionPath(id), JSON.stringify(rec, null, 2), 'utf8');
64
- }
65
- function endSession(id, summary) {
66
- const rec = readSession(id);
67
- if (!rec)
68
- return;
69
- rec.endedAt = new Date().toISOString();
70
- if (summary)
71
- rec.summary = summary;
72
- fs_1.default.writeFileSync(sessionPath(id), JSON.stringify(rec, null, 2), 'utf8');
73
- }
74
- //# sourceMappingURL=store.js.map
@@ -1,39 +0,0 @@
1
- /**
2
- * Chunking Manager for Large ServiceNow Artifacts
3
- * Handles scripts >30k characters that exceed API token limits
4
- */
5
- export interface ChunkingStrategy {
6
- maxChunkSize: number;
7
- overlapSize: number;
8
- chunkType: 'lines' | 'functions' | 'blocks';
9
- }
10
- export interface ScriptChunk {
11
- index: number;
12
- content: string;
13
- startLine: number;
14
- endLine: number;
15
- type: 'complete' | 'partial_start' | 'partial_middle' | 'partial_end';
16
- hasContext: boolean;
17
- }
18
- export declare class ChunkingManager {
19
- /**
20
- * Determine if script needs chunking
21
- */
22
- static needsChunking(script: string, maxSize?: number): boolean;
23
- /**
24
- * Split large script into manageable chunks
25
- */
26
- static chunkScript(script: string, strategy?: ChunkingStrategy): ScriptChunk[];
27
- /**
28
- * Generate instructions for manual large script handling
29
- */
30
- static generateManualInstructions(scriptName: string, scriptSize: number, chunks: ScriptChunk[]): string;
31
- /**
32
- * Attempt smart chunked update for large scripts
33
- */
34
- static attemptChunkedUpdate(client: any, table: string, sys_id: string, field: string, script: string): Promise<{
35
- success: boolean;
36
- message: string;
37
- }>;
38
- }
39
- //# sourceMappingURL=chunking-manager.d.ts.map
@@ -1,142 +0,0 @@
1
- "use strict";
2
- /**
3
- * Chunking Manager for Large ServiceNow Artifacts
4
- * Handles scripts >30k characters that exceed API token limits
5
- */
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.ChunkingManager = void 0;
8
- class ChunkingManager {
9
- /**
10
- * Determine if script needs chunking
11
- */
12
- static needsChunking(script, maxSize = 100000) {
13
- return script.length > maxSize;
14
- }
15
- /**
16
- * Split large script into manageable chunks
17
- */
18
- static chunkScript(script, strategy = {
19
- maxChunkSize: 25000,
20
- overlapSize: 500,
21
- chunkType: 'functions'
22
- }) {
23
- const lines = script.split('\n');
24
- const chunks = [];
25
- if (!this.needsChunking(script)) {
26
- return [{
27
- index: 0,
28
- content: script,
29
- startLine: 1,
30
- endLine: lines.length,
31
- type: 'complete',
32
- hasContext: true
33
- }];
34
- }
35
- let currentChunk = '';
36
- let currentStartLine = 1;
37
- let chunkIndex = 0;
38
- for (let i = 0; i < lines.length; i++) {
39
- const line = lines[i];
40
- const potentialChunk = currentChunk + line + '\n';
41
- if (potentialChunk.length > strategy.maxChunkSize) {
42
- // Current chunk is full, save it
43
- if (currentChunk.trim()) {
44
- chunks.push({
45
- index: chunkIndex++,
46
- content: currentChunk.trim(),
47
- startLine: currentStartLine,
48
- endLine: i,
49
- type: chunkIndex === 0 ? 'partial_start' : 'partial_middle',
50
- hasContext: true
51
- });
52
- }
53
- // Start new chunk with overlap
54
- const overlapLines = Math.min(Math.floor(strategy.overlapSize / 50), // Assume ~50 chars per line
55
- 10 // Max 10 lines overlap
56
- );
57
- const overlapStart = Math.max(0, i - overlapLines);
58
- currentChunk = lines.slice(overlapStart, i + 1).join('\n') + '\n';
59
- currentStartLine = overlapStart + 1;
60
- }
61
- else {
62
- currentChunk += line + '\n';
63
- }
64
- }
65
- // Add final chunk
66
- if (currentChunk.trim()) {
67
- chunks.push({
68
- index: chunkIndex,
69
- content: currentChunk.trim(),
70
- startLine: currentStartLine,
71
- endLine: lines.length,
72
- type: 'partial_end',
73
- hasContext: true
74
- });
75
- }
76
- return chunks;
77
- }
78
- /**
79
- * Generate instructions for manual large script handling
80
- */
81
- static generateManualInstructions(scriptName, scriptSize, chunks) {
82
- return `
83
- 🚨 LARGE SCRIPT DETECTED: ${scriptName} (${scriptSize.toLocaleString()} characters)
84
-
85
- ⚠️ This script exceeds API token limits and cannot be updated automatically.
86
-
87
- 🔧 MANUAL UPDATE REQUIRED:
88
-
89
- 1. **Navigate to ServiceNow**:
90
- - Go to Service Portal → Widgets
91
- - Find and edit your widget
92
- - Click on "Server Script" tab
93
-
94
- 2. **Copy the updated script**:
95
- - Script has been split into ${chunks.length} chunks below
96
- - Copy ALL chunks in order and paste into ServiceNow
97
-
98
- 3. **Chunks to copy**:
99
- ${chunks.map(chunk => `
100
- **Chunk ${chunk.index + 1}/${chunks.length}** (Lines ${chunk.startLine}-${chunk.endLine}):
101
- \`\`\`javascript
102
- ${chunk.content.substring(0, 500)}${chunk.content.length > 500 ? '...\n[truncated for display]' : ''}
103
- \`\`\`
104
- `).join('')}
105
-
106
- 4. **Validation**:
107
- - Ensure no syntax errors after pasting
108
- - Test widget functionality
109
- - Consider breaking into smaller Script Includes
110
-
111
- 💡 **Prevention for future**:
112
- - Keep server scripts under 30,000 characters
113
- - Use Script Includes for reusable functions
114
- - Move complex logic to business rules where appropriate
115
- `;
116
- }
117
- /**
118
- * Attempt smart chunked update for large scripts
119
- */
120
- static async attemptChunkedUpdate(client, table, sys_id, field, script) {
121
- if (!this.needsChunking(script)) {
122
- // Not chunked, do normal update
123
- try {
124
- await client.updateRecord(table, sys_id, { [field]: script });
125
- return { success: true, message: 'Script updated successfully' };
126
- }
127
- catch (error) {
128
- return { success: false, message: `Update failed: ${error}` };
129
- }
130
- }
131
- // For large scripts, we can't actually chunk the API call
132
- // But we can provide intelligent guidance
133
- const chunks = this.chunkScript(script);
134
- const instructions = this.generateManualInstructions(field, script.length, chunks);
135
- return {
136
- success: false,
137
- message: `Script too large for automatic update. Manual steps required:\n${instructions}`
138
- };
139
- }
140
- }
141
- exports.ChunkingManager = ChunkingManager;
142
- //# sourceMappingURL=chunking-manager.js.map